holochain

package module
v0.0.1-alpha Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 8, 2017 License: GPL-3.0 Imports: 60 Imported by: 0

README

Holochain

Code Status Travis Codecov Go Report Card Gitter In Progress Twitter Follow

Holographic storage for distributed applications. A holochain is a monotonic distributed hash table (DHT) where every node enforces validation rules on data before publishing that data against the signed chains where the data originated.

In other words, a holochain functions very much like a blockchain without bottlenecks when it comes to enforcing validation rules, but is designed to be fully distributed with each node only needing to hold a small portion of the data instead of everything needing a full copy of a global ledger. This makes it feasible to run blockchain-like applications on devices as lightweight as mobile phones.

Code Status: Alpha. Not for production use. The code has not yet undergone a security audit. We expect to destructively restructure code APIs and data chains until Beta. Proof-of-concept was unveiled at our first hackathon (March 2017). Alpha 0 was released (October 2017).

Holochain Links: FAQ Developer Wiki White Paper GoDocs

Table of Contents

Installation

Developers Only: At this stage, holochain is only for use by developers (either developers of applications to run on holochains, or developers of the holochain software itself). App developers should bundle their app in an installer as either approach below is not for non-technical folks.

There are two approaches to installing holochain:

  1. as a standard Go language application for direct execution on your machine
  2. using docker for execution in a container.

Which you choose depends on your preference and your purpose. If you intend to develop holochain applications, then you should almost certainly use the docker approach as we provide a testing harness for running multiple holochain instances in a docker cluster. If you will be developing in Go on holochain itself then you will probably end up doing both.

Go Based Install
  1. Download Go. Download the "Archive" or "Installer" for version 1.8 or later for your CPU and OS. The "Source" download does not contain an executable and step 3 will fail.
  2. Install Go on your system. See platform specific instructions and hints below for making this work.
  3. Install the command line tool suite with:
$ go get -d -v github.com/metacurrency/holochain
$ cd $GOPATH/src/github.com/metacurrency/holochain
$ make
  1. Test that it works (should look something like this):
$ hcadmin -v
hcadmin version 0.0.x (holochain y)
Unix

(Unix includes macOS and Linux.) You'll need to have a working environment set up for Go version 1.8 or later. See the installation instructions for Go.

Most importantly you'll need to: (Almost all installation problems that have been reported stem from skipping one of these steps.)

  1. Export the $GOPATH variable in your shell profile.
  2. Add $GOPATH/bin to your $PATH in your shell profile.

For example, add the following to the end of your shell profile (usually ~/.bashrc or ~/.bash_profile):

export GOPATH="$HOME/go"
export PATH="$GOPATH/bin:$PATH"
Windows

First you'll need to install some necessary programs if you don't already have them.

  • Download Go. Download the "Archive" or "Installer" for version 1.8 or later for Windows and your CPU. The "Source" download does not contain an executable.
  • Install Windows git. Be sure to select the appropriate options so that git is accessible from the Windows command line.
  • Optional: Install GnuWin32 make.

Next, in your Control Panel, select System>Advanced system settings>Environment Variables... and under System Variables do the following:

  1. Add a new entry with the name GOPATH and the value %USERPROFILE%\go (Or your Go workspace folder).
  2. Double-click Path, and in the window that pops up add the following entries:
    • %GOPATH%\bin
    • C:\Go\bin (Or wherever you installed Go to+\bin).
    • C:\Program Files (x86)\GnuWin32\bin (Or wherever you installed GnuWin32 make to+\bin).
Docker Based Install

Using docker, you don't have to install Go first. Our docker scripts manage installation of Go, holochain dependencies and holochain. The docker installation can run alongside Local ("Go") installation of holochain, sharing config directories. See docker usage on our wiki for more on how this works.

  1. Install the latest version of Docker on your machine
    1. Docker Installation. The Community edition; stable is sufficient.
    2. See Docker Getting Started for help.
    3. It is recommended to add your user to the docker group as in: Post Installation Steps, rather than use sudo before all script commands. Holochain Apps cannot exploit the kinds of security concerns mentioned in the Post Installation Steps document.  
  2. Confirm that docker installation and permissions are working by running:
$ docker info
  1. Get our holochain repository from github:
$ git clone https://github.com/metacurrency/holochain.git holochain
$ cd holochain
  1. Build the holochain core with all dependencies
$ docker/build
  • the first time build is run on a machine, it will download Alpine unix, and install all holochain dependencies.
  • During development cycles, docker/build will just compile changes made to the holochain go code, and run tests
  1. To run holochain in your new environment, suitable to continue the walkthrough below in usage
$ docker/run
  1. This will put you into an new command shell that may behave differently than what you're used to. To exit this holochain (Alpine) shell, press Ctrl-D or type exit

Usage

These instructions are for using the holochain command line tool suite: hcadmin, hcdev and hcd. They should work equally well for Go based or docker based installation.

(Note that since Holochain is intended to be used behind distributed applications, end users should not have to do much through the command or may not have it installed at all, as the application will probably have wrapped up the holochain library internally.)

Each of the tools includes a help command, e.g., run hcadmin help or for sub-commands run hcadmin <COMMAND> help. For more detailed information, see the wiki page

The tool suite include these commands:

  • hcadmin for administering your installed holochain applications
  • hcd for running and serving a holochain application
  • hcdev for developing and testing holochain applications
Getting Started

The instructions below walk you through the basic steps necessary to run a holochain application.

Initializing the Holochain environment
$ hcadmin init 'your@emailaddress.here'

This command creates a ~/.holochain directory for storing all chain data, along with initial public/private key pairs based on the identity string provided as the second argument.

Joining a Holochain

You can use the hcadmin tool to join a pre-existing Holochain application by running the following command (replacing SOURCE_PATH with a path to an application's DNA and CHAIN_NAME with the name you'd like it to be stored as).

For example: hcadmin join ./examples/chat chat

Note: this command will be replaced by a package management command still in development.

Running a Holochain

Holochains run and serve their UI via local web sockets. This let's interface developers have a lot of freedom to build HTML/JavaScript files and drop them in that chain's UI directory. You start a holochain and activate it's UI with the hcd command:

$ hcd <CHAIN_NAME> [PORT]
Developing a Holochain

The hcdev tool allows you to:

  1. generate new holochain application source files by cloning from an existing application, from the a package file, or a simple empty template.
  2. run stand-alone or multi-node scenario tests
  3. run a holochain and serve it's UI for testing purposes
  4. dump out chain and dht data for inspection

Please see the wiki for more detailed documentation.

Note that the hcdev command creates a separate ~/.holochaindev directory for serving and managing chains, so your dev work won't interfere with any running holochain apps you may be using.

Test-driven Application Development

We have designed Holochain around test-driven development, so the DNA should contain tests to confirm that the rest of the DNA is functional. Our testing harness includes two types of testing, stand-alone and multi-instance scenarios. Stand-alone tests allow you to tests the functions you create in your application. However, testing a distributed application requires being able to spin up many instances of it and have them interact. Our docker cluster testing harness automates that process, and enables app developers to specify scenarios and roles and test instructions to run on multiple docker containers.

Please see the App-Testing documentation for details.

File Locations

By default holochain data and configuration files are assumed to be stored in the ~/.holochain directory. You can override this with the -path flag or by setting the HOLOPATH environment variable, e.g.:

$ hcadmin -path ~/mychains init '<my@other.identity>'
$ HOLOPATH=~/mychains hcadmin

You can use the form: hcadmin -path=/your/path/here but you must use the absolute path, as shell substitutions will not happen.

Logging

All the commands take a --debug flag which will turn on a number of different kinds of debugging. For running chains, you can also control exactly which of these logging types you wish to see in the chain's config.json file. You can also set the DEBUG environment variable to 0 or 1 to temporarily override your settings to turn everything on or off.

Architecture Overview and Documentation

Architecture information and application developer documentation is in our Holochain Wiki.

You can also look through auto-generated reference API on GoDocs

Holochain Core Development

We accept Pull Requests and welcome your participation.

Some helpful links: In Progress

If you'd like to get involved you can:

  • Contact us on Gitter to set up a pair coding session with one of our developers to learn the lay of the land.
  • join our dev documentation calls twice weekly on Tuesdays and Fridays.

Current Throughput graph:

Throughput Graph

Contribute

Contributors to this project are expected to follow our development protocols & practices.

Dependencies

This project depends on various parts of libp2p, which uses the gx package manager. All of which will be automatically installed by make by following the setup instructions above.

Tests

To compile and run all the tests:

$ cd $GOPATH/github.com/metacurrency/holochain
$ make test

If you want to use go test instead of make test, you'll need to do a couple extra things because of this project's dependency on gx:

  • Before running go test you need to run make work to configure the imports properly.
  • If you do this, before commiting you must also run make pub to revert the changes it makes.

The docker setup runs tests automatically during builds.

License

Copyright (C) 2017, The MetaCurrency Project (Eric Harris-Braun, Arthur Brock, et. al.)

This program is free software: you can redistribute it and/or modify it under the terms of the license provided in the LICENSE file (GPLv3). This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Note: We are considering other 'looser' licensing options (like MIT license) but at this stage are using GPL while we're getting the matter sorted out.

Acknowledgements

  • MetaCurrency & Ceptr: Holochains are a sub-project of Ceptr which is a semantic, distributed computing platform under development by the MetaCurrency Project.  
  • Ian Grigg: Some of our initial plans for this architecture were inspired in 2006 by his paper about Triple Entry Accounting and his work on Ricardian Contracts.  
  • Juan Benet & the IPFS team: For all their work on IPFS, libp2p, and various cool tools like multihash, multiaddress, etc. We use libP2P library for our transport layer and kademlia dht.  
  • Crypto Pioneers And of course the people who paved the road before us by writing good crypto libraries and preaching the blockchain gospel. Back in 2008, nobody understood what we were talking about when we started sharing our designs. The main reason people want it now, is because blockchains have opened their eyes to the power of decentralized architectures.

Documentation

Overview

Copyright (C) 2013-2017, The MetaCurrency Project (Eric Harris-Braun, Arthur Brock, et. al.) Use of this source code is governed by GPLv3 found in the LICENSE file ----------------------------------------------------------------------------------------

package holochain should be imported by go packages intending to create a UI for this holochain implementation.

An example of a package which imports holochain is https://github.com/metacurrency/holochain/tree/master/cmd/hc

For information not found here see the wiki:

https://github.com/metacurrency/holochain/wiki

or the repo:

https://github.com/metacurrency/holochain

If you are here because you intend to develop an application built on holochain take a look at the App Developer sections of the wiki.

If you would like a description of the architecture/technical aspects of holochain look at those sections of the wiki.

Data integrity engine for distributed applications -- a validating monotonic DHT "backed" by authoritative hashchains for data provenance.

Copyright (C) 2013-2017, The MetaCurrency Project (Eric Harris-Braun, Arthur Brock, et. al.) Use of this source code is governed by GPLv3 found in the LICENSE file ----------------------------------------------------------------------------------------

This code is adapted from the libp2p project, specifically: https://github.com/libp2p/go-libp2p-kad-dht/notif.go

The ipfs use of kademlia is substantially different than that needed by holochain so we remove parts we don't need and add others.

Index

Constants

View Source
const (
	HashArg = iota
	StringArg
	EntryArg // special arg type for entries, can be a string or a hash
	IntArg
	BoolArg
	MapArg
	ToStrArg // special arg type that converts anything to a string, used for the debug action
	ArgsArg  // special arg type for arguments passed to the call action
)

these constants define the argument types for actions, i.e. system functions callable from within nuclei

View Source
const (
	DHTChangeOK = iota
	DHTChangeUnknownHashQueuedForRetry
)
View Source
const (
	ChainMarshalFlagsNone            = 0x00
	ChainMarshalFlagsNoHeaders       = 0x01
	ChainMarshalFlagsNoEntries       = 0x02
	ChainMarshalFlagsOmitDNA         = 0x04
	ChainMarshalFlagsNoPrivate       = 0x08
	ChainMarshalPrivateEntryRedacted = "%%PRIVATE ENTRY REDACTED%%"
)
View Source
const (
	AddAction = ""
	ModAction = "m"
	DelAction = "d"

	StatusDefault  = 0x00
	StatusLive     = 0x01
	StatusRejected = 0x02
	StatusDeleted  = 0x04
	StatusModified = 0x08
	StatusAny      = 0xFF

	StatusLiveVal     = "1"
	StatusRejectedVal = "2"
	StatusDeletedVal  = "4"
	StatusModifiedVal = "8"
	StatusAnyVal      = "255"

	SysTagReplacedBy = "__replacedBy"

	GetMaskDefault   = 0x00
	GetMaskEntry     = 0x01
	GetMaskEntryType = 0x02
	GetMaskSources   = 0x04
	GetMaskAll       = 0xFF

	GetMaskDefaultStr   = "0"
	GetMaskEntryStr     = "1"
	GetMaskEntryTypeStr = "2"
	GetMaskSourcesStr   = "4"
	GetMaskAllStr       = "255"
)
View Source
const (
	GossipWithQueueSize = 10
	GossipPutQueueSize  = 1000
)
View Source
const (
	SysEntryTypePrefix     = "%"
	VirtualEntryTypePrefix = "%%"

	DNAEntryType   = SysEntryTypePrefix + "dna"
	AgentEntryType = SysEntryTypePrefix + "agent"
	KeyEntryType   = VirtualEntryTypePrefix + "key" // virtual entry type, not actually on the chain

	DataFormatLinks    = "links"
	DataFormatJSON     = "json"
	DataFormatString   = "string"
	DataFormatRawJS    = "js"
	DataFormatRawZygo  = "zygo"
	DataFormatSysDNA   = "_DNA"
	DataFormatSysAgent = "_agent"
	DataFormatSysKey   = "_key"

	Public  = "public"
	Partial = "partial"
	Private = "private"
)
View Source
const (
	// Version is the numeric version number of the holochain library
	Version int = 18

	// VersionStr is the textual version number of the holochain library
	VersionStr string = "18"

	// DefaultSendTimeout a time.Duration to wait by default for send to complete
	DefaultSendTimeout = 3000 * time.Millisecond
)
View Source
const (
	ActionProtocol = iota
	ValidateProtocol
	GossipProtocol
	KademliaProtocol
)
View Source
const (
	PeerTTL                       = time.Minute * 10
	DefaultRoutingRefreshInterval = time.Minute
	DefaultGossipInterval         = time.Second * 2
)
View Source
const (
	ErrUnknownCode = iota
	ErrHashNotFoundCode
	ErrHashDeletedCode
	ErrHashModifiedCode
	ErrHashRejectedCode
	ErrLinkNotFoundCode
	ErrEntryTypeMismatchCode
	ErrBlockedListedCode
)
View Source
const (
	STRING_CALLING = "string"
	JSON_CALLING   = "json"

	// ZOME_EXPOSURE is the default and means the function is only exposed for use by other zomes in the app
	ZOME_EXPOSURE = ""
	// AUTHENTICATED_EXPOSURE means that the function is only available after authentication (TODO)
	AUTHENTICATED_EXPOSURE = "auth"
	// PUBLIC_EXPOSURE means that the function is callable by anyone
	PUBLIC_EXPOSURE = "public"

	ID_PROPERTY         = "_id"
	AGENT_ID_PROPERTY   = "_agent_id"
	AGENT_NAME_PROPERTY = "_agent_name"

	BridgeFrom    = 0
	BridgeTo      = 1
	BridgeFromStr = "0"
	BridgeToStr   = "1"
)
View Source
const (
	DefaultDirectoryName string = ".holochain"  // Directory for storing config data
	ChainDataDir         string = "db"          // Sub-directory for all chain content files
	ChainDNADir          string = "dna"         // Sub-directory for all chain definition files
	ChainUIDir           string = "ui"          // Sub-directory for all chain user interface files
	ChainTestDir         string = "test"        // Sub-directory for all chain test files
	DNAFileName          string = "dna"         // Definition of the Holochain
	ConfigFileName       string = "config"      // Settings of the Holochain
	SysFileName          string = "system.conf" // Server & System settings
	AgentFileName        string = "agent.txt"   // User ID info
	PrivKeyFileName      string = "priv.key"    // Signing key - private
	StoreFileName        string = "chain.db"    // Filename for local data store
	DNAHashFileName      string = "dna.hash"    // Filename for storing the hash of the holochain
	DHTStoreFileName     string = "dht.db"      // Filname for storing the dht
	BridgeDBFileName     string = "bridge.db"   // Filname for storing bridge keys

	TestConfigFileName string = "_config.json"

	DefaultPort            = 6283
	DefaultBootstrapServer = "bootstrap.holochain.net:10000"

	DefaultBootstrapServerEnvVar = "HC_DEFAULT_BOOTSTRAPSERVER"
	DefaultEnableMDNSEnvVar      = "HC_DEFAULT_ENABLEMDNS"
	DefaultEnableNATUPnPEnvVar   = "HC_DEFAULT_ENABLENATUPNP"

	CloneWithNewUUID  = true
	CloneWithSameUUID = false
	InitializeDB      = true
	SkipInitializeDB  = false
)

System settings, directory, and file names

View Source
const (
	SampleHTML = `` /* 821-byte string literal not displayed */

	SampleJS = `` /* 440-byte string literal not displayed */

	SampleBinary = `` /* 3713-byte string literal not displayed */

)
View Source
const (
	OS_READ        = 04
	OS_WRITE       = 02
	OS_EX          = 01
	OS_USER_SHIFT  = 6
	OS_GROUP_SHIFT = 3
	OS_OTH_SHIFT   = 0

	OS_USER_R   = OS_READ << OS_USER_SHIFT
	OS_USER_W   = OS_WRITE << OS_USER_SHIFT
	OS_USER_X   = OS_EX << OS_USER_SHIFT
	OS_USER_RW  = OS_USER_R | OS_USER_W
	OS_USER_RWX = OS_USER_RW | OS_USER_X

	OS_GROUP_R   = OS_READ << OS_GROUP_SHIFT
	OS_GROUP_W   = OS_WRITE << OS_GROUP_SHIFT
	OS_GROUP_X   = OS_EX << OS_GROUP_SHIFT
	OS_GROUP_RW  = OS_GROUP_R | OS_GROUP_W
	OS_GROUP_RWX = OS_GROUP_RW | OS_GROUP_X

	OS_OTH_R   = OS_READ << OS_OTH_SHIFT
	OS_OTH_W   = OS_WRITE << OS_OTH_SHIFT
	OS_OTH_X   = OS_EX << OS_OTH_SHIFT
	OS_OTH_RW  = OS_OTH_R | OS_OTH_W
	OS_OTH_RWX = OS_OTH_RW | OS_OTH_X

	OS_ALL_R   = OS_USER_R | OS_GROUP_R | OS_OTH_R
	OS_ALL_W   = OS_USER_W | OS_GROUP_W | OS_OTH_W
	OS_ALL_X   = OS_USER_X | OS_GROUP_X | OS_OTH_X
	OS_ALL_RW  = OS_ALL_R | OS_ALL_W
	OS_ALL_RWX = OS_ALL_RW | OS_GROUP_X
)
View Source
const (

	// PkgReqChain is the key who value is one of the PkgReqChainOptX masks
	PkgReqChain = "chain"

	// PkgReqEntryTypes is the key who value is an array of entry types to limit
	// the chain to
	PkgReqEntryTypes = "types"

	PkgReqChainOptNone       = 0x00
	PkgReqChainOptHeaders    = 0x01
	PkgReqChainOptEntries    = 0x02
	PkgReqChainOptFull       = 0x03
	PkgReqChainOptNoneStr    = "0"
	PkgReqChainOptHeadersStr = "1"
	PkgReqChainOptEntriesStr = "2"
	PkgReqChainOptFullStr    = "3"
)
View Source
const (
	AppPackageVersion = "0.0.1"
)
View Source
const (
	BasicTemplateAppPackageFormat = "yml"
)
View Source
const (
	BlockedList = "blockedlist"
)
View Source
const (
	BootstrapTTL = time.Minute * 5
)
View Source
const (
	DefaultRetryInterval = time.Millisecond * 500
)
View Source
const (
	GossipBackPutDelay = 100 * time.Millisecond
)
View Source
const (
	JSLibrary = `var HC={Version:` + `"` + VersionStr + "\"" +
		`,Status:{Live:` + StatusLiveVal +
		`,Rejected:` + StatusRejectedVal +
		`,Deleted:` + StatusDeletedVal +
		`,Modified:` + StatusModifiedVal +
		`,Any:` + StatusAnyVal +
		"}" +
		`,GetMask:{Default:` + GetMaskDefaultStr +
		`,Entry:` + GetMaskEntryStr +
		`,EntryType:` + GetMaskEntryTypeStr +
		`,Sources:` + GetMaskSourcesStr +
		`,All:` + GetMaskAllStr +
		"}" +
		`,LinkAction:{Add:"` + AddAction + `",Del:"` + DelAction + `"}` +
		`,PkgReq:{Chain:"` + PkgReqChain + `"` +
		`,ChainOpt:{None:` + PkgReqChainOptNoneStr +
		`,Headers:` + PkgReqChainOptHeadersStr +
		`,Entries:` + PkgReqChainOptEntriesStr +
		`,Full:` + PkgReqChainOptFullStr +
		"}" +
		"}" +
		`,Bridge:{From:` + BridgeFromStr +
		`,To:` + BridgeToStr +
		"}" +
		`};`
)
View Source
const (
	JSRibosomeType = "js"
)
View Source
const (
	LibP2P = iota
)
View Source
const (
	MaxRetries = 10
)
View Source
const (
	SelfRevocationType = iota
)
View Source
const (
	TestingAppDecodingFormat = "json"
)
View Source
const (
	ZygoLibrary = `(def HC_Version "` + VersionStr + `")` +
		`(def HC_Status_Live ` + StatusLiveVal + ")" +
		`(def HC_Status_Rejected ` + StatusRejectedVal + ")" +
		`(def HC_Status_Deleted ` + StatusDeletedVal + ")" +
		`(def HC_Status_Modified ` + StatusModifiedVal + ")" +
		`(def HC_Status_Any ` + StatusAnyVal + ")" +
		`(def HC_GetMask_Default ` + GetMaskDefaultStr + ")" +
		`(def HC_GetMask_Entry ` + GetMaskEntryStr + ")" +
		`(def HC_GetMask_EntryType ` + GetMaskEntryTypeStr + ")" +
		`(def HC_GetMask_Sources ` + GetMaskSourcesStr + ")" +
		`(def HC_GetMask_All ` + GetMaskAllStr + ")" +

		`(def HC_Bridge_From ` + BridgeFromStr + ")" +
		`(def HC_Bridge_To ` + BridgeToStr + ")" +

		`(def HC_LinkAction_Add "` + AddAction + "\")" +
		`(def HC_LinkAction_Del "` + DelAction + "\")" +
		`(def HC_PkgReq_Chain "` + PkgReqChain + "\")" +
		`(def HC_PkgReq_ChainOpt_None "` + PkgReqChainOptNoneStr + "\")" +
		`(def HC_PkgReq_ChainOpt_Headers "` + PkgReqChainOptHeadersStr + "\")" +
		`(def HC_PkgReq_ChainOpt_Entries "` + PkgReqChainOptEntriesStr + "\")" +
		`(def HC_PkgReq_ChainOpt_Full "` + PkgReqChainOptFullStr + "\")"
)

These are the zygo implementations of the library functions that must available in all Ribosome implementations.

View Source
const (
	ZygoRibosomeType = "zygo"
)

Variables

View Source
var AgentEntryDef = &EntryDef{Name: AgentEntryType, DataFormat: DataFormatSysAgent}
View Source
var AlphaValue int = 3
View Source
var BasicTemplateAppPackage string = `{
 # AppPackage Version
 # The app package schema version of this file.
"Version": "` + AppPackageVersion + `",
"Generator": "holochain",

"DNA": {
  # This is a holochain application package yaml definition. http://ceptr.org/projects/holochain

  # DNA File Version
  # Version indicator for changes to DNA
  "Version": 1,

  # DNA Unique ID
  # This ID differentiates your app from others. For example, to tell one Slack team from another with same code, so change it!
  "UUID": "00000000-0000-0000-0000-000000000000",

  # Application Name
  # What would you like to call your holochain app?
  "Name": "templateApp",

  # Requires Holochain Version
  # Version indicator for which minimal version of holochain is required by this DNA
  "RequiresVersion": ` + VersionStr + `,

  # Properties
  # Properties that you want available across all Zomes.
  "Properties": {

    # Application Description
    # Briefly describe your holochain app.
    "description": "provides an application template",

    # Language
    # The base (human) language of this holochain app.
    "language": "en"
  },

  # Properties Schema File
  # Describes the entries in the Properties section of your dna file.
  "PropertiesSchemaFile": "properties_schema.json",

  # DHT Settings
  # Configure the properties of your Distributed Hash Table (e.g. hash algorithm, neighborhood size, etc.).
  "DHTConfig": {
    "HashType": "sha2-256"
  },

  # Zomes
  # List the Zomes your application will support.
  "Zomes": [
    {

      # Zome Name
      # The name of this code module.
      "Name": "sampleZome",

      # Zome Description
      # What is the purpose of this module?
      "Description": "provide a sample zome",

      # Ribosome Type
      # What scripting language will you code in?
      "RibosomeType": "js",

      # Zome Entries
      # Data stored and tracked by your Zome.
      "Entries": [
        {
          "Name": "sampleEntry", # The name of this entry.
          "Required": true, # Is this entry required?
          "DataFormat": "json", # What type of data should this entry store?
          "Sharing": "public", # Should this entry be publicly accessible?
          "Schema": "{\n	\"title\": \"sampleEntry Schema\",\n	\"type\": \"object\",\n	\"properties\": {\n		\"content\": {\n			\"type\": \"string\"\n		},\n		\"timestamp\": {\n			\"type\": \"integer\"\n		}\n	},\n    \"required\": [\"body\", \"timestamp\"]\n}",
          "_": "cr"
        }
      ],

      # Zome Functions
      # Functions which can be called in your Zome's API.
      "Functions": [
        {
          "Name": "sampleEntryCreate", # The name of this function.
          "CallingType": "json", # Data format for parameters passed to this function.
          "Exposure": "public", # Level to which is this function exposed.
          "_": "c:sampleEntry"
        },
        {
          "Name": "sampleEntryRead", # The name of this function.
          "CallingType": "json", # Data format for parameters passed to this function.
          "Exposure": "public", # Level to which is this function exposed.
          "_": "r:sampleEntry"
        },
        {
          "Name": "doSampleAction", # The name of this function.
          "CallingType": "json", # Data format for parameters passed to this function.
          "Exposure": "public" # Level to which is this function exposed.
        }
      ],

      # Zome Source Code
      # The logic that will control Zome behavior
      "Code": "'use strict';\n\n// -----------------------------------------------------------------\n//  This stub Zome code file was auto-generated\n// -----------------------------------------------------------------\n\n/**\n * Called only when your source chain is generated\n * @return {boolean} success\n */\nfunction genesis() {\n  // any genesis code here\n  return true;\n}\n\n// -----------------------------------------------------------------\n//  validation functions for every DHT entry change\n// -----------------------------------------------------------------\n\n/**\n * Called to validate any changes to the DHT\n * @param {string} entryName - the name of entry being modified\n * @param {*} entry - the entry data to be set\n * @param {?} header - ?\n * @param {?} pkg - ?\n * @param {?} sources - ?\n * @return {boolean} is valid?\n */\nfunction validateCommit (entryName, entry, header, pkg, sources) {\n  switch (entryName) {\n    case \"sampleEntry\":\n      // validation code here\n      return false;\n    default:\n      // invalid entry name!!\n      return false;\n  }\n}\n\n/**\n * Called to validate any changes to the DHT\n * @param {string} entryName - the name of entry being modified\n * @param {*}entry - the entry data to be set\n * @param {?} header - ?\n * @param {?} pkg - ?\n * @param {?} sources - ?\n * @return {boolean} is valid?\n */\nfunction validatePut (entryName, entry, header, pkg, sources) {\n  switch (entryName) {\n    case \"sampleEntry\":\n      // validation code here\n      return false;\ndefault:\n      // invalid entry name!!\n      return false;\n  }\n}\n\n/**\n * Called to validate any changes to the DHT\n * @param {string} entryName - the name of entry being modified\n * @param {*} entry- the entry data to be set\n * @param {?} header - ?\n * @param {*} replaces - the old entry data\n * @param {?} pkg - ?\n * @param {?} sources - ?\n * @return {boolean} is valid?\n */\nfunction validateMod (entryName, entry, header, replaces, pkg, sources) {\n  switch (entryName) {\n    case \"sampleEntry\":\n      // validation code here\n      return false;\n    default:\n      // invalid entry name!!\n      return false;\n  }\n}\n\n/**\n * Called to validate any changes to the DHT\n * @param {string} entryName - the name of entry being modified\n * @param {string} hash - the hash of the entry to remove\n * @param {?} pkg - ?\n * @param {?} sources - ?\n * @return {boolean} is valid?\n */\nfunction validateDel (entryName,hash, pkg, sources) {\n  switch (entryName) {\n    case \"sampleEntry\":\n      // validation code here\nreturn false;\n    default:\n      // invalid entry name!!\n      return false;\n  }\n}\n\n/**\n * Called to get the data needed to validate\n * @param {string} entryName - the name of entry to validate\n * @return {*} the data required for validation\n */\nfunction validatePutPkg (entryName) {\n  return null;\n}\n\n/**\n * Called to get the data needed to validate\n * @param {string} entryName - the name of entry to validate\n * @return {*} the data required for validation\n */\nfunction validateModPkg (entryName) {\n  return null;\n}\n\n/**\n * Called to get the data needed to validate\n * @param {string} entryName - the name of entry to validate\n * @return {*} the data required for validation\n */\nfunction validateDelPkg (entryName) {\n  return null;\n}"
    }
  ]},
"TestSets":[{
  "Name":"sample",
  "TestSet":{"Tests":[{"Convey":"We can create a new sampleEntry","FnName": "sampleEntryCreate","Input": {"body": "this is the entry body","stamp":12345},"Output":"\"%h1%\"","Exposure":"public"}]}}
   ],
"UI":[
{"FileName":"index.html",
 "Data":"<html><body>Your UI here!</body></html>"
},
{"FileName":"hc.js",
 "Data":"function yourApp(){alert('your UI code here!')}"
}],
"Scenarios":[
        {"Name":"sampleScenario",
         "Roles":[
             {"Name":"listener",
              "TestSet":{"Tests":[
                  {"Convey":"add listener test here"}]}},
             {"Name":"speaker",
              "TestSet":{"Tests":[
                  {"Convey":"add speaker test here"}]}}],
         "Config":{"Duration":5,"GossipInterval":100}}]
}
`
View Source
var BridgeAppNotFoundErr = errors.New("bridge app not found")
View Source
var CapabilityInvalidErr = errors.New("invalid capability")
View Source
var ChangeAppProperty = Change{
	Type:    Warning,
	Message: "Getting special properties via property() is deprecated as of %d. Returning nil values.  Use App* instead",
	AsOf:    3,
}
View Source
var CloserPeerCount = KValue

The number of closer peers to send on requests.

View Source
var Crash bool
View Source
var DNAEntryDef = &EntryDef{Name: DNAEntryType, DataFormat: DataFormatSysDNA}
View Source
var DevDNAResolveMap map[string]string
View Source
var EnableAllLoggersEnv string = "HC_ENABLE_ALL_LOGS"
View Source
var ErrBlockedListed = errors.New("node blockedlisted")
View Source
var ErrDHTErrNoGossipersAvailable error = errors.New("no gossipers available")
View Source
var ErrDHTExpectedGossipReqInBody error = errors.New("expected gossip request")
View Source
var ErrDHTUnexpectedTypeInBody error = errors.New("unexpected type in message body")
View Source
var ErrEmptyRoutingTable = errors.New("routing table empty")
View Source
var ErrEntryTypeMismatch = errors.New("entry type mismatch")
View Source
var ErrHashDeleted = errors.New("hash deleted")
View Source
var ErrHashModified = errors.New("hash modified")
View Source
var ErrHashNotFound = errors.New("hash not found")
View Source
var ErrHashRejected = errors.New("hash rejected")
View Source
var ErrIncompleteChain = errors.New("operation not allowed on incomplete chain")
View Source
var ErrLinkNotFound = errors.New("link not found")
View Source
var ErrNilEntryInvalid error = errors.New("nil entry invalid")
View Source
var ErrNoSuchIdx error = errors.New("no such change index")
View Source
var ErrNotValidForAgentType error = errors.New("Invalid action for Agent type")
View Source
var ErrNotValidForDNAType error = errors.New("Invalid action for DNA type")
View Source
var ErrNotValidForKeyType error = errors.New("Invalid action for Key type")
View Source
var ErrPutLinkOverDeleted = errors.New("putlink over deleted link")
View Source
var ErrWrongNargs = errors.New("wrong number of arguments")
View Source
var IsDevMode bool = false

IsDevMode is used to enable certain functionality when developing holochains, for example, in dev mode, you can put the name of an app in the BridgeTo of the DNA and it will get resolved to DNA hash of the app in the DevDNAResolveMap[name] global variable.

View Source
var KValue int = 10
View Source
var KeyEntryDef = &EntryDef{Name: KeyEntryType, DataFormat: DataFormatSysKey}
View Source
var NonCallableAction error = errors.New("Not a callable action")
View Source
var NonDHTAction error = errors.New("Not a DHT action")
View Source
var SelfRevocationDoesNotVerify = errors.New("self revocation does not verify")
View Source
var SendTimeoutErr = errors.New("send timeout")
View Source
var UnknownWarrantTypeErr = errors.New("unknown warrant type")
View Source
var ValidationFailedErr = errors.New("Validation Failed")
View Source
var WarrantPropertyNotFoundErr = errors.New("warrant property not found")

Functions

func ActionReceiver

func ActionReceiver(h *Holochain, msg *Message) (response interface{}, err error)

ActionReceiver handles messages on the action protocol

func BootstrapRefreshTask

func BootstrapRefreshTask(h *Holochain)

BootstrapRefreshTask refreshes our node and gets nodes from the bootstrap server

func ByteDecoder

func ByteDecoder(b []byte, to interface{}) (err error)

ByteDecoder decodes data encoded by ByteEncoder

func ByteEncoder

func ByteEncoder(data interface{}) (b []byte, err error)

ByteEncoder encodes anything using gob

func CleanupTestChain

func CleanupTestChain(h *Holochain, d string)

func CleanupTestDir

func CleanupTestDir(path string)

func CopyDir

func CopyDir(source string, dest string) (err error)

CopyDir recursively copies a directory tree, attempting to preserve permissions. Source directory must exist, destination directory must *not* exist.

func CopyFile

func CopyFile(source string, dest string) (err error)

CopyFile copies file source to destination dest.

func DNAHashofUngenedChain

func DNAHashofUngenedChain(h *Holochain) (DNAHash Hash, err error)

func Debug

func Debug(m string)

Debug sends a string to the standard debug log

func Debugf

func Debugf(m string, args ...interface{})

Debugf sends a formatted string to the global debug log

func DebuggingRequestedViaEnv

func DebuggingRequestedViaEnv() (val, yes bool)

DebuggingRequestedViaEnv determines whether an environment var was set to enable or disable debugging

func Decode

func Decode(reader io.Reader, format string, data interface{}) (err error)

Decode extracts data from the reader according to the type

func DirExists

func DirExists(pathParts ...string) bool

func Encode

func Encode(writer io.Writer, format string, data interface{}) (err error)

Encode encodes data to the writer according to the given format

func EncodingFormat

func EncodingFormat(file string) (f string)

EncodingFormat returns the files format if supported otherwise ""

func FileExists

func FileExists(pathParts ...string) bool

func GetAllTestRoles

func GetAllTestRoles(path string) (roleNameList []string, err error)

GetAllTestRoles retuns a list of the roles in a scenario

func GetTestScenarioRoles

func GetTestScenarioRoles(h *Holochain, scenarioName string) (roleNameList []string, err error)

GetTestScenarioRoles returns a list of scenario roles

func GetTestScenarios

func GetTestScenarios(h *Holochain) (scenarios map[string]*os.FileInfo, err error)

TestScenarioList returns a list of paths to scenario directories

func GossipReceiver

func GossipReceiver(h *Holochain, m *Message) (response interface{}, err error)

GossipReceiver implements the handler for the gossip protocol

func GossipTask

func GossipTask(h *Holochain)

GossipTask runs a gossip and logs any errors

func Info

func Info(m string)

Info sends a string to the global info log

func Infof

func Infof(m string, args ...interface{})

Infof sends a formatted string to the standard info log

func InitializeHolochain

func InitializeHolochain()

InitializeHolochain setup function that must be called once at startup by the application that uses this holochain library

func IsInitialized

func IsInitialized(root string) bool

IsInitialized checks a path for a correctly set up .holochain directory

func KademliaReceiver

func KademliaReceiver(h *Holochain, m *Message) (response interface{}, err error)

KademliaReceiver implements the handler for the kademlia RPC protocol messages

func LoadTestFiles

func LoadTestFiles(path string) (map[string]TestSet, error)

LoadTestFiles searches a path for .json test files and loads them into an array

func MakeDirs

func MakeDirs(devPath string) error

MakeDirs creates the directory structure of an application

func MakeTestDirName

func MakeTestDirName() string

func MakeTestSeed

func MakeTestSeed(id string) io.Reader

func MarshalEntry

func MarshalEntry(writer io.Writer, e Entry) (err error)

MarshalEntry serializes an entry to a writer

func MarshalHeader

func MarshalHeader(writer io.Writer, hd *Header) (err error)

MarshalHeader writes a header to a binary stream

func MarshalSignature

func MarshalSignature(writer io.Writer, s *Signature) (err error)

MarshalSignature writes a signature to a binary stream

func Panix

func Panix(on string)

func PrepareTestChain

func PrepareTestChain(n string) (d string, s *Service, h *Holochain)

func ReadFile

func ReadFile(pathParts ...string) (data []byte, err error)

func RegisterBultinRibosomes

func RegisterBultinRibosomes()

RegisterBultinRibosomes adds the built in ribosome types to the factory hash

func RegisterRibosome

func RegisterRibosome(name string, factory RibosomeFactory)

RegisterRibosome sets up a Ribosome to be used by the CreateRibosome function

func RetryTask

func RetryTask(h *Holochain)

Retry starts retry processing

func RoutingRefreshTask

func RoutingRefreshTask(h *Holochain)

RoutingRefreshTask fills the routing table by searching for a random node

func RunValidationPhase

func RunValidationPhase(h *Holochain, source peer.ID, msgType MsgType, query Hash, handler func(resp ValidateResponse) error) (err error)

func SaveAgent

func SaveAgent(path string, agent Agent) (err error)

SaveAgent saves out the keys and agent name to the given directory

func SetupTestChain

func SetupTestChain(n string) (d string, s *Service, h *Holochain)

func SetupTestDir

func SetupTestDir() string

func ShouldLog

func ShouldLog(log *Logger, message string, fn func())

func SortClosestPeers

func SortClosestPeers(peers []peer.ID, target Hash) []peer.ID

func TestingAppAppPackage

func TestingAppAppPackage() string

func Ticker

func Ticker(interval time.Duration, fn func()) (stopper chan bool)

Ticker runs a function on an interval that can be stopped with the returned bool channel

func UnmarshalHeader

func UnmarshalHeader(reader io.Reader, hd *Header, hashSize int) (err error)

UnmarshalHeader reads a Header from a binary stream

func UnmarshalSignature

func UnmarshalSignature(reader io.Reader, s *Signature) (err error)

UnmarshalSignature reads a Signature from a binary stream

func ValidateReceiver

func ValidateReceiver(h *Holochain, msg *Message) (response interface{}, err error)

ValidateReceiver handles messages on the Validate protocol

func WriteFile

func WriteFile(data []byte, pathParts ...string) error

Types

type Action

type Action interface {
	Name() string
	Do(h *Holochain) (response interface{}, err error)
	Receive(dht *DHT, msg *Message, retries int) (response interface{}, err error)
	Args() []Arg
}

Action provides an abstraction for grouping all the aspects of a nucleus function, i.e. the initiating actions, receiving them, validation, ribosome generation etc

func MakeActionFromMessage

func MakeActionFromMessage(msg *Message) (a Action, err error)

MakeActionFromMessage generates an action from an action protocol messsage

type ActionBridge

type ActionBridge struct {
	// contains filtered or unexported fields
}

func NewBridgeAction

func NewBridgeAction(zome string, function string, args interface{}) *ActionBridge

func (*ActionBridge) Args

func (a *ActionBridge) Args() []Arg

func (*ActionBridge) Do

func (a *ActionBridge) Do(h *Holochain) (response interface{}, err error)

func (*ActionBridge) Name

func (a *ActionBridge) Name() string

type ActionCall

type ActionCall struct {
	// contains filtered or unexported fields
}

func NewCallAction

func NewCallAction(zome string, function string, args interface{}) *ActionCall

func (*ActionCall) Args

func (a *ActionCall) Args() []Arg

func (*ActionCall) Do

func (a *ActionCall) Do(h *Holochain) (response interface{}, err error)

func (*ActionCall) Name

func (a *ActionCall) Name() string

type ActionCommit

type ActionCommit struct {
	// contains filtered or unexported fields
}

func NewCommitAction

func NewCommitAction(entryType string, entry Entry) *ActionCommit

func (*ActionCommit) Args

func (a *ActionCommit) Args() []Arg

func (*ActionCommit) CheckValidationRequest

func (a *ActionCommit) CheckValidationRequest(def *EntryDef) (err error)

func (*ActionCommit) Do

func (a *ActionCommit) Do(h *Holochain) (response interface{}, err error)

func (*ActionCommit) Entry

func (a *ActionCommit) Entry() Entry

func (*ActionCommit) EntryType

func (a *ActionCommit) EntryType() string

func (*ActionCommit) Name

func (a *ActionCommit) Name() string

func (*ActionCommit) Receive

func (a *ActionCommit) Receive(dht *DHT, msg *Message, retries int) (response interface{}, err error)

func (*ActionCommit) SetHeader

func (a *ActionCommit) SetHeader(header *Header)

func (*ActionCommit) SysValidation

func (a *ActionCommit) SysValidation(h *Holochain, def *EntryDef, pkg *Package, sources []peer.ID) (err error)

type ActionDebug

type ActionDebug struct {
	// contains filtered or unexported fields
}

func NewDebugAction

func NewDebugAction(msg string) *ActionDebug

func (*ActionDebug) Args

func (a *ActionDebug) Args() []Arg

func (*ActionDebug) Do

func (a *ActionDebug) Do(h *Holochain) (response interface{}, err error)

func (*ActionDebug) Name

func (a *ActionDebug) Name() string

type ActionDel

type ActionDel struct {
	// contains filtered or unexported fields
}

func NewDelAction

func NewDelAction(entryType string, entry DelEntry) *ActionDel

func (*ActionDel) Args

func (a *ActionDel) Args() []Arg

func (*ActionDel) CheckValidationRequest

func (a *ActionDel) CheckValidationRequest(def *EntryDef) (err error)

func (*ActionDel) Do

func (a *ActionDel) Do(h *Holochain) (response interface{}, err error)

func (*ActionDel) Entry

func (a *ActionDel) Entry() Entry

func (*ActionDel) EntryType

func (a *ActionDel) EntryType() string

func (*ActionDel) Name

func (a *ActionDel) Name() string

func (*ActionDel) Receive

func (a *ActionDel) Receive(dht *DHT, msg *Message, retries int) (response interface{}, err error)

func (*ActionDel) SetHeader

func (a *ActionDel) SetHeader(header *Header)

func (*ActionDel) SysValidation

func (a *ActionDel) SysValidation(h *Holochain, def *EntryDef, pkg *Package, sources []peer.ID) (err error)

type ActionGet

type ActionGet struct {
	// contains filtered or unexported fields
}

------------------------------------------------------------ Get

func NewGetAction

func NewGetAction(req GetReq, options *GetOptions) *ActionGet

func (*ActionGet) Args

func (a *ActionGet) Args() []Arg

func (*ActionGet) Do

func (a *ActionGet) Do(h *Holochain) (response interface{}, err error)

func (*ActionGet) Name

func (a *ActionGet) Name() string

func (*ActionGet) Receive

func (a *ActionGet) Receive(dht *DHT, msg *Message, retries int) (response interface{}, err error)

func (*ActionGet) SysValidation

func (a *ActionGet) SysValidation(h *Holochain, def *EntryDef, pkg *Package, sources []peer.ID) (err error)

type ActionGetBridges

type ActionGetBridges struct {
}

func NewGetBridgesAction

func NewGetBridgesAction(doc []byte) *ActionGetBridges

func (*ActionGetBridges) Args

func (a *ActionGetBridges) Args() []Arg

func (*ActionGetBridges) Do

func (a *ActionGetBridges) Do(h *Holochain) (response interface{}, err error)

func (*ActionGetBridges) Name

func (a *ActionGetBridges) Name() string
type ActionGetLinks struct {
	// contains filtered or unexported fields
}

func NewGetLinksAction

func NewGetLinksAction(linkQuery *LinkQuery, options *GetLinksOptions) *ActionGetLinks

func (*ActionGetLinks) Args

func (a *ActionGetLinks) Args() []Arg

func (*ActionGetLinks) Do

func (a *ActionGetLinks) Do(h *Holochain) (response interface{}, err error)

func (*ActionGetLinks) Name

func (a *ActionGetLinks) Name() string

func (*ActionGetLinks) Receive

func (a *ActionGetLinks) Receive(dht *DHT, msg *Message, retries int) (response interface{}, err error)

func (*ActionGetLinks) SysValidation

func (a *ActionGetLinks) SysValidation(h *Holochain, d *EntryDef, pkg *Package, sources []peer.ID) (err error)
type ActionLink struct {
	// contains filtered or unexported fields
}

func NewLinkAction

func NewLinkAction(entryType string, links []Link) *ActionLink

func (*ActionLink) Args

func (a *ActionLink) Args() []Arg

func (*ActionLink) CheckValidationRequest

func (a *ActionLink) CheckValidationRequest(def *EntryDef) (err error)

func (*ActionLink) Do

func (a *ActionLink) Do(h *Holochain) (response interface{}, err error)

func (*ActionLink) Name

func (a *ActionLink) Name() string

func (*ActionLink) Receive

func (a *ActionLink) Receive(dht *DHT, msg *Message, retries int) (response interface{}, err error)

func (*ActionLink) SysValidation

func (a *ActionLink) SysValidation(h *Holochain, def *EntryDef, pkg *Package, sources []peer.ID) (err error)

type ActionListAdd

type ActionListAdd struct {
	// contains filtered or unexported fields
}

func NewListAddAction

func NewListAddAction(peerList PeerList) *ActionListAdd

func (*ActionListAdd) Args

func (a *ActionListAdd) Args() []Arg

func (*ActionListAdd) Do

func (a *ActionListAdd) Do(h *Holochain) (response interface{}, err error)

func (*ActionListAdd) Name

func (a *ActionListAdd) Name() string

func (*ActionListAdd) Receive

func (a *ActionListAdd) Receive(dht *DHT, msg *Message, retries int) (response interface{}, err error)

type ActionMakeHash

type ActionMakeHash struct {
	// contains filtered or unexported fields
}

func NewMakeHashAction

func NewMakeHashAction(entry Entry) *ActionMakeHash

func (*ActionMakeHash) Args

func (a *ActionMakeHash) Args() []Arg

func (*ActionMakeHash) Do

func (a *ActionMakeHash) Do(h *Holochain) (response interface{}, err error)

func (*ActionMakeHash) Name

func (a *ActionMakeHash) Name() string

type ActionMod

type ActionMod struct {
	// contains filtered or unexported fields
}

func NewModAction

func NewModAction(entryType string, entry Entry, replaces Hash) *ActionMod

func (*ActionMod) Args

func (a *ActionMod) Args() []Arg

func (*ActionMod) CheckValidationRequest

func (a *ActionMod) CheckValidationRequest(def *EntryDef) (err error)

func (*ActionMod) Do

func (a *ActionMod) Do(h *Holochain) (response interface{}, err error)

func (*ActionMod) Entry

func (a *ActionMod) Entry() Entry

func (*ActionMod) EntryType

func (a *ActionMod) EntryType() string

func (*ActionMod) Name

func (a *ActionMod) Name() string

func (*ActionMod) Receive

func (a *ActionMod) Receive(dht *DHT, msg *Message, retries int) (response interface{}, err error)

func (*ActionMod) SetHeader

func (a *ActionMod) SetHeader(header *Header)

func (*ActionMod) SysValidation

func (a *ActionMod) SysValidation(h *Holochain, def *EntryDef, pkg *Package, sources []peer.ID) (err error)

type ActionModAgent

type ActionModAgent struct {
	Identity   AgentIdentity
	Revocation string
}

func NewModAgentAction

func NewModAgentAction(identity AgentIdentity) *ActionModAgent

func (*ActionModAgent) Args

func (a *ActionModAgent) Args() []Arg

func (*ActionModAgent) Do

func (a *ActionModAgent) Do(h *Holochain) (response interface{}, err error)

func (*ActionModAgent) Name

func (a *ActionModAgent) Name() string

type ActionProperty

type ActionProperty struct {
	// contains filtered or unexported fields
}

func NewPropertyAction

func NewPropertyAction(prop string) *ActionProperty

func (*ActionProperty) Args

func (a *ActionProperty) Args() []Arg

func (*ActionProperty) Do

func (a *ActionProperty) Do(h *Holochain) (response interface{}, err error)

func (*ActionProperty) Name

func (a *ActionProperty) Name() string

type ActionPut

type ActionPut struct {
	// contains filtered or unexported fields
}

func NewPutAction

func NewPutAction(entryType string, entry Entry, header *Header) *ActionPut

func (*ActionPut) Args

func (a *ActionPut) Args() []Arg

func (*ActionPut) CheckValidationRequest

func (a *ActionPut) CheckValidationRequest(def *EntryDef) (err error)

func (*ActionPut) Do

func (a *ActionPut) Do(h *Holochain) (response interface{}, err error)

func (*ActionPut) Name

func (a *ActionPut) Name() string

func (*ActionPut) Receive

func (a *ActionPut) Receive(dht *DHT, msg *Message, retries int) (response interface{}, err error)

func (*ActionPut) SysValidation

func (a *ActionPut) SysValidation(h *Holochain, def *EntryDef, pkg *Package, sources []peer.ID) (err error)

type ActionQuery

type ActionQuery struct {
	// contains filtered or unexported fields
}

func NewQueryAction

func NewQueryAction(options *QueryOptions) *ActionQuery

func (*ActionQuery) Args

func (a *ActionQuery) Args() []Arg

func (*ActionQuery) Do

func (a *ActionQuery) Do(h *Holochain) (response interface{}, err error)

func (*ActionQuery) Name

func (a *ActionQuery) Name() string

type ActionSend

type ActionSend struct {
	// contains filtered or unexported fields
}

func NewSendAction

func NewSendAction(to peer.ID, msg AppMsg) *ActionSend

func (*ActionSend) Args

func (a *ActionSend) Args() []Arg

func (*ActionSend) Do

func (a *ActionSend) Do(h *Holochain) (response interface{}, err error)

func (*ActionSend) Name

func (a *ActionSend) Name() string

func (*ActionSend) Receive

func (a *ActionSend) Receive(dht *DHT, msg *Message, retries int) (response interface{}, err error)

type ActionSign

type ActionSign struct {
	// contains filtered or unexported fields
}

func NewSignAction

func NewSignAction(doc []byte) *ActionSign

func (*ActionSign) Args

func (a *ActionSign) Args() []Arg

func (*ActionSign) Do

func (a *ActionSign) Do(h *Holochain) (response interface{}, err error)

func (*ActionSign) Name

func (a *ActionSign) Name() string

type ActionVerifySignature

type ActionVerifySignature struct {
	// contains filtered or unexported fields
}

------------------------------------------------------------ VerifySignature

func NewVerifySignatureAction

func NewVerifySignatureAction(signature string, data string, pubKey string) *ActionVerifySignature

func (*ActionVerifySignature) Args

func (a *ActionVerifySignature) Args() []Arg

func (*ActionVerifySignature) Do

func (a *ActionVerifySignature) Do(h *Holochain) (response bool, err error)

func (*ActionVerifySignature) Name

func (a *ActionVerifySignature) Name() string

type Agent

type Agent interface {
	Identity() AgentIdentity
	SetIdentity(id AgentIdentity)
	AgentType() AgentType
	GenKeys(seed io.Reader) error
	PrivKey() ic.PrivKey
	PubKey() ic.PubKey
	NodeID() (peer.ID, string, error)
	AgentEntry(revocation Revocation) (AgentEntry, error)
}

Agent abstracts the key behaviors and connection to a holochain node address Note that this is currently only a partial abstraction because the NodeID is always a libp2p peer.ID to complete the abstraction so we could use other libraries for p2p2 network transaction we would need to also abstract a matching NodeID type

func LoadAgent

func LoadAgent(path string) (agent Agent, err error)

LoadAgent gets the agent identity and private key from the specified directory TODO confirm against chain?

func NewAgent

func NewAgent(agentType AgentType, identity AgentIdentity, seed io.Reader) (agent Agent, err error)

NewAgent creates an agent structure of the given type Note: currently only IPFS agents are implemented

type AgentEntry

type AgentEntry struct {
	Identity   AgentIdentity
	Revocation []byte // marshaled revocation
	PublicKey  []byte // marshaled public key
}

AgentEntry structure for building AgentEntryType entries

type AgentFixture

type AgentFixture struct {
	Hash     string
	Identity string
}

AgentFixture defines an agent for the purposes of tests

type AgentIdentity

type AgentIdentity string

AgentIdentity is the user's unique identity information in context of this holochain. it follows AgentIdentitySchema in DNA

type AgentType

type AgentType int

type AppMsg

type AppMsg struct {
	ZomeType string
	Body     string
}

type AppPackage

type AppPackage struct {
	Version   string
	Generator string
	DNA       DNA
	TestSets  []AppPackageTests
	UI        []AppPackageUIFile
	Scenarios []AppPackageScenario
}

func LoadAppPackage

func LoadAppPackage(reader io.Reader, encodingFormat string) (appPackageP *AppPackage, err error)

LoadAppPackage decodes DNA and other appPackage data from appPackage file (via an io.reader)

type AppPackageScenario

type AppPackageScenario struct {
	Name   string
	Roles  []AppPackageTests
	Config TestConfig
}

type AppPackageTests

type AppPackageTests struct {
	Name    string
	TestSet TestSet
}

type AppPackageUIFile

type AppPackageUIFile struct {
	FileName string
	Data     string
	Encoding string
}

type Arg

type Arg struct {
	Name     string
	Type     ArgType
	Optional bool
	MapType  reflect.Type
	// contains filtered or unexported fields
}

type ArgType

type ArgType int8

type BSReq

type BSReq struct {
	Version  int
	NodeID   string
	NodeAddr string
}

type BSResp

type BSResp struct {
	Req      BSReq
	Remote   string
	LastSeen time.Time
}

type Bridge

type Bridge struct {
	ToApp Hash
	Token string
	Side  int
}

Bridge holds data returned by GetBridges

type BridgeApp

type BridgeApp struct {
	H                     *Holochain
	Side                  int
	BridgeGenesisDataFrom string
	BridgeGenesisDataTo   string
	Port                  string // only used if side == BridgeTo
}

BridgeApp describes an app for bridging, used

type BridgeSpec

type BridgeSpec map[string]map[string]bool

type Bucket

type Bucket struct {
	// contains filtered or unexported fields
}

Bucket holds a list of peers.

func (*Bucket) Has

func (b *Bucket) Has(id peer.ID) bool

func (*Bucket) Len

func (b *Bucket) Len() int

func (*Bucket) MoveToFront

func (b *Bucket) MoveToFront(id peer.ID)

func (*Bucket) Peers

func (b *Bucket) Peers() []peer.ID

func (*Bucket) PopBack

func (b *Bucket) PopBack() peer.ID

func (*Bucket) PushFront

func (b *Bucket) PushFront(p peer.ID)

func (*Bucket) Remove

func (b *Bucket) Remove(id peer.ID)

func (*Bucket) Split

func (b *Bucket) Split(cpl int, target peer.ID) *Bucket

Split splits a buckets peers into two buckets, the methods receiver will have peers with CPL equal to cpl, the returned bucket will have peers with CPL greater than cpl (returned bucket has closer peers)

type Callback

type Callback struct {
	Function string
	ID       string
	// contains filtered or unexported fields
}

type Capability

type Capability struct {
	Token string
	// contains filtered or unexported fields
}

func NewCapability

func NewCapability(db *buntdb.DB, capability string, who interface{}) (c *Capability, err error)

NewCapability returns and registers a capability of a type, for a specific or anyone if who is nil

func (*Capability) Revoke

func (c *Capability) Revoke(who interface{}) (err error)

Revoke unregisters the capability for a peer

func (*Capability) Validate

func (c *Capability) Validate(who interface{}) (capability string, err error)

Validate checks to see if the token has been registered and returns the capability it represent

type Chain

type Chain struct {
	Hashes   []Hash
	Headers  []*Header
	Entries  []Entry
	TypeTops map[string]int // pointer to index of top of a given type
	Hmap     map[string]int // map header hashes to index number
	Emap     map[string]int // map entry hashes to index number
	// contains filtered or unexported fields
}

Chain structure for providing in-memory access to chain data, entries headers and hashes

func NewChain

func NewChain(hashSpec HashSpec) (chain *Chain)

NewChain creates and empty chain

func NewChainFromFile

func NewChainFromFile(spec HashSpec, path string) (c *Chain, err error)

NewChainFromFile creates a chain from a file, loading any data there, and setting it to be persisted to. If no file exists it will be created.

func UnmarshalChain

func UnmarshalChain(hashSpec HashSpec, reader io.Reader) (flags int64, c *Chain, err error)

UnmarshalChain unserializes a chain from a reader

func (*Chain) AddEntry

func (c *Chain) AddEntry(now time.Time, entryType string, e Entry, privKey ic.PrivKey) (hash Hash, err error)

AddEntry creates a new header and adds it to a chain

func (*Chain) Close

func (c *Chain) Close()

Close the chain's file

func (*Chain) Get

func (c *Chain) Get(h Hash) (header *Header, err error)

Get returns the header of a given hash

func (*Chain) GetEntry

func (c *Chain) GetEntry(h Hash) (entry Entry, entryType string, err error)

GetEntry returns the entry of a given entry hash

func (*Chain) GetEntryHeader

func (c *Chain) GetEntryHeader(h Hash) (header *Header, err error)

GetEntryHeader returns the header of a given entry hash

func (*Chain) Length

func (c *Chain) Length() int

Length returns the number of entries in the chain

func (*Chain) MarshalChain

func (c *Chain) MarshalChain(writer io.Writer, flags int64, whitelistTypes []string, privateTypes []string) (err error)

MarshalChain serializes a chain data to a writer

func (*Chain) Nth

func (c *Chain) Nth(n int) (header *Header)

Nth returns the nth latest header

func (*Chain) String

func (c *Chain) String() string

String converts a chain to a textual dump of the headers and entries

func (*Chain) Top

func (c *Chain) Top() (header *Header)

Top returns the latest header

func (*Chain) TopType

func (c *Chain) TopType(entryType string) (hash *Hash, header *Header)

TopType returns the latest header of a given type

func (*Chain) Validate

func (c *Chain) Validate(skipEntries bool) (err error)

Validate traverses chain confirming the hashes @TODO confirm that TypeLinks are also correct @TODO confirm signatures

func (*Chain) Walk

func (c *Chain) Walk(fn WalkerFn) (err error)

Walk traverses chain from most recent to first entry calling fn on each one

type ChainPair

type ChainPair struct {
	Header *Header
	Entry  Entry
}

type Change

type Change struct {
	Type    ChangeType
	Message string
	AsOf    int
}

Change represents a semantic change that needs to be reported

func (*Change) Log

func (c *Change) Log()

type ChangeType

type ChangeType int8
const (
	Deprecation ChangeType = iota
	Warning
)

type CloneSpec

type CloneSpec struct {
	Role   string
	Number int
}

type CloserPeersResp

type CloserPeersResp struct {
	CloserPeers []PeerInfo // note this is not a pstore.PeerInfo which can't be serialized by gob.
}

type CommittingAction

type CommittingAction interface {
	Name() string
	Do(h *Holochain) (response interface{}, err error)
	SysValidation(h *Holochain, def *EntryDef, pkg *Package, sources []peer.ID) (err error)
	Receive(dht *DHT, msg *Message, retries int) (response interface{}, err error)
	CheckValidationRequest(def *EntryDef) (err error)
	Args() []Arg
	EntryType() string
	Entry() Entry
	SetHeader(header *Header)
}

CommittingAction provides an abstraction for grouping actions which carry Entry data

type Config

type Config struct {
	Port            int
	EnableMDNS      bool
	PeerModeAuthor  bool
	PeerModeDHTNode bool
	EnableNATUPnP   bool
	BootstrapServer string
	Loggers         Loggers
	// contains filtered or unexported fields
}

Config holds the non-DNA configuration for a holo-chain, from config file or environment variables

func (*Config) SetGossipInterval

func (config *Config) SetGossipInterval(interval time.Duration)

func (*Config) Setup

func (config *Config) Setup() (err error)

func (*Config) SetupLogging

func (config *Config) SetupLogging() (err error)

SetupLogging initializes loggers as configured by the config file and environment variables

type DHT

type DHT struct {
	// contains filtered or unexported fields
}

DHT struct holds the data necessary to run the distributed hash table

func NewDHT

func NewDHT(h *Holochain) *DHT

NewDHT creates a new DHT structure

func (*DHT) AddGossiper

func (dht *DHT) AddGossiper(id peer.ID) (err error)

AddGossiper adds a new gossiper to the gossiper store

func (*DHT) Change

func (dht *DHT) Change(key Hash, msgType MsgType, body interface{}) (err error)

Change sends DHT change messages to the closest peers to the hash in question

func (*DHT) Close

func (dht *DHT) Close()

Close cleans up the DHT

func (*DHT) DeleteGossiper

func (dht *DHT) DeleteGossiper(id peer.ID) (err error)

DeleteGossiper removes a gossiper from the database

func (*DHT) DumpIdx

func (dht *DHT) DumpIdx(idx int) (str string, err error)

DumpIdx converts message and data of a DHT change request to a string for human consumption

func (*DHT) FindGossiper

func (dht *DHT) FindGossiper() (g peer.ID, err error)

FindGossiper picks a random DHT node to gossip with

func (*DHT) GetFingerprint

func (dht *DHT) GetFingerprint(f Hash) (index int, err error)

GetFingerprint returns the index that of the message that made a change or -1 if we don't have it

func (*DHT) GetGossiper

func (dht *DHT) GetGossiper(id peer.ID) (idx int, err error)

GetGossiper loads returns last known index of the gossiper, and adds them if not didn't exist before

func (*DHT) GetIdx

func (dht *DHT) GetIdx() (idx int, err error)

GetIdx returns the current put index for gossip

func (*DHT) GetIdxMessage

func (dht *DHT) GetIdxMessage(idx int) (msg Message, err error)

GetIdxMessage returns the messages that causes the change at a given index

func (*DHT) GetPuts

func (dht *DHT) GetPuts(since int) (puts []Put, err error)

GetPuts returns a list of puts after the given index

func (*DHT) HandleGossipPuts

func (dht *DHT) HandleGossipPuts() (err error)

HandleGossipPuts waits on a channel for gossip changes

func (*DHT) HandleGossipWiths

func (dht *DHT) HandleGossipWiths() (err error)

HandleGossipWiths waits on a channel for gossipWith requests

func (*DHT) HaveFingerprint

func (dht *DHT) HaveFingerprint(f Hash) (result bool, err error)

HaveFingerprint returns true if we have seen the given fingerprint

func (*DHT) Query

func (dht *DHT) Query(key Hash, msgType MsgType, body interface{}) (response interface{}, err error)

Query sends DHT query messages recursively to peers until one is able to respond.

func (*DHT) SetupDHT

func (dht *DHT) SetupDHT() (err error)

SetupDHT prepares a DHT for use by putting the genesis entries that are added by GenChain

func (*DHT) Start

func (dht *DHT) Start() (err error)

Start initiates listening for DHT & Gossip protocol messages on the node

func (*DHT) String

func (dht *DHT) String() (result string)

String converts a DHT into a human readable string

func (*DHT) UpdateGossiper

func (dht *DHT) UpdateGossiper(id peer.ID, newIdx int) (err error)

UpdateGossiper updates a gossiper

type DHTConfig

type DHTConfig struct {
	// HashType : (string) Identifies hash type to be used for this application. Should be from the list of hash types from the multihash library
	HashType string

	// NeighborhoodSize(integer) Establishes minimum online redundancy targets for data, and size of peer sets for sync gossip. A neighborhood size of ZERO means no sharding (every node syncs all data with every other node). ONE means you are running this as a centralized application and gossip is turned OFF. For most applications we recommend neighborhoods no smaller than 8 for nearness or 32 for hashmask sharding.
	NeighborhoodSize int
}

Holds the dht configuration options

type DNA

type DNA struct {
	Version             int
	UUID                uuid.UUID
	Name                string
	Properties          map[string]string
	PropertiesSchema    string
	AgentIdentitySchema string // defines what must go in the Indentity field of a key/agent entry
	BasedOn             Hash   // references hash of another holochain that these schemas and code are derived from
	RequiresVersion     int
	DHTConfig           DHTConfig
	Progenitor          Progenitor
	Zomes               []Zome
	// contains filtered or unexported fields
}

func (*DNA) NewUUID

func (dna *DNA) NewUUID() (err error)

NewUUID generates a new UUID for the DNA

type DNAFile

type DNAFile struct {
	Version              int
	UUID                 uuid.UUID
	Name                 string
	Properties           map[string]string
	PropertiesSchemaFile string
	BasedOn              Hash // references hash of another holochain that these schemas and code are derived from
	Zomes                []ZomeFile
	RequiresVersion      int
	DHTConfig            DHTConfig
	Progenitor           Progenitor
}

type DelEntry

type DelEntry struct {
	Hash    Hash
	Message string
}

DelEntry struct holds the record of an entry's deletion

type DelReq

type DelReq struct {
	H  Hash // hash to be deleted
	By Hash // hash of DelEntry on source chain took this action
}

DelReq holds the data of a del request

type Entry

type Entry interface {
	Marshal() ([]byte, error)
	Unmarshal([]byte) error
	Content() interface{}
	Sum(s HashSpec) (hash Hash, err error)
}

Entry describes serialization and deserialziation of entry data

func UnmarshalEntry

func UnmarshalEntry(reader io.Reader) (e Entry, err error)

UnmarshalEntry unserializes an entry from a reader

type EntryDef

type EntryDef struct {
	Name       string
	DataFormat string
	Sharing    string
	Schema     string
	// contains filtered or unexported fields
}

EntryDef struct holds an entry definition

func (*EntryDef) BuildJSONSchemaValidator

func (d *EntryDef) BuildJSONSchemaValidator(path string) (err error)

BuildJSONSchemaValidator builds a validator in an EntryDef

func (*EntryDef) BuildJSONSchemaValidatorFromString

func (d *EntryDef) BuildJSONSchemaValidatorFromString(schema string) (err error)

func (*EntryDef) IsSysEntry

func (def *EntryDef) IsSysEntry() bool

IsSysEntry returns true if the entry type is system defined

func (*EntryDef) IsVirtualEntry

func (def *EntryDef) IsVirtualEntry() bool

IsVirtualEntry returns true if the entry type is virtual

type EntryDefFile

type EntryDefFile struct {
	Name       string
	DataFormat string
	Schema     string
	SchemaFile string // file name of schema or language schema directive
	Sharing    string
}

type ErrorResponse

type ErrorResponse struct {
	Code    int
	Message string
	Payload interface{}
}

func NewErrorResponse

func NewErrorResponse(err error) (errResp ErrorResponse)

NewErrorResponse encodes standard errors for transmitting

func (ErrorResponse) DecodeResponseError

func (errResp ErrorResponse) DecodeResponseError() (err error)

DecodeResponseError creates a go error object from the ErrorResponse data

type FindNodeReq

type FindNodeReq struct {
	H Hash
}

type FunctionDef

type FunctionDef struct {
	Name        string
	CallingType string
	Exposure    string
}

FunctionDef holds the name and calling type of an DNA exposed function

func (*FunctionDef) ValidExposure

func (f *FunctionDef) ValidExposure(context string) bool

ValidExposure verifies that the function can be called in the given context

type GetLinksOptions

type GetLinksOptions struct {
	Load       bool // indicates whether GetLinks should retrieve the entries of all links
	StatusMask int  // mask of which status of links to return
}

GetLinksOptions options to holochain level GetLinks functions

type GetOptions

type GetOptions struct {
	StatusMask int  // mask of which status of entries to return
	GetMask    int  // mask of what to include in the response
	Local      bool // bool if get should happen from chain not DHT
}

GetOptions options to holochain level Get functions

type GetReq

type GetReq struct {
	H          Hash
	StatusMask int
	GetMask    int
}

GetReq holds the data of a get request

type GetResp

type GetResp struct {
	Entry      GobEntry
	EntryType  string
	Sources    []string
	FollowHash string // hash of new entry if the entry was modified and needs following
}

GetResp holds the data of a get response

type GobEntry

type GobEntry struct {
	C interface{}
}

GobEntry is a structure for implementing Gob encoding of Entry content

func (*GobEntry) Content

func (e *GobEntry) Content() interface{}

func (*GobEntry) Marshal

func (e *GobEntry) Marshal() (b []byte, err error)

func (*GobEntry) Sum

func (e *GobEntry) Sum(s HashSpec) (h Hash, err error)

func (*GobEntry) Unmarshal

func (e *GobEntry) Unmarshal(b []byte) (err error)

type Gossip

type Gossip struct {
	Puts []Put
}

Gossip holds a gossip message

type GossipReq

type GossipReq struct {
	MyIdx   int
	YourIdx int
}

GossipReq holds a gossip request

type Header struct {
	Type       string
	Time       time.Time
	HeaderLink Hash // link to previous headerq
	EntryLink  Hash // link to entry
	TypeLink   Hash // link to header of previous header of this type
	Sig        Signature
	Change     StatusChange
}

Header holds chain links, type, timestamp and signature

func (*Header) Marshal

func (hd *Header) Marshal() (b []byte, err error)

Marshal writes a header to bytes

func (*Header) Sum

func (hd *Header) Sum(spec HashSpec) (hash Hash, b []byte, err error)

Sum encodes and creates a hash digest of the header

func (*Header) Unmarshal

func (hd *Header) Unmarshal(b []byte, hashSize int) (err error)

Unmarshal reads a header from bytes

type Holochain

type Holochain struct {
	Config Config
	// contains filtered or unexported fields
}

Holochain struct holds the full "DNA" of the holochain (all your app code for managing distributed data integrity)

func NewHolochain

func NewHolochain(agent Agent, root string, format string, zomes ...Zome) Holochain

NewHolochain creates a new holochain structure with a randomly generated ID and default values

func (*Holochain) Activate

func (h *Holochain) Activate() (err error)

Activate fires up the holochain node, starting node discovery and protocols

func (*Holochain) AddAgentEntry

func (h *Holochain) AddAgentEntry(revocation Revocation) (headerHash, agentHash Hash, err error)

AddAgentEntry adds a new sys entry type setting the current agent data (identity and key)

func (*Holochain) AddBridgeAsCallee

func (h *Holochain) AddBridgeAsCallee(fromDNA Hash, appData string) (token string, err error)

AddBridgeAsCallee registers a token for allowing bridged calls from some other app and calls bridgeGenesis in any zomes with bridge functions

func (*Holochain) AddBridgeAsCaller

func (h *Holochain) AddBridgeAsCaller(toDNA Hash, token string, url string, appData string) (err error)

AddBridgeAsCaller associates a token with an application DNA hash and url for accessing it it also runs BridgeGenesis for the From side

func (*Holochain) AddPeer

func (h *Holochain) AddPeer(pi pstore.PeerInfo) (err error)

AddPeer adds a peer to the peerstore if it passes various checks

func (*Holochain) Agent

func (h *Holochain) Agent() Agent

Agent exposes the agent element

func (*Holochain) AgentHash

func (h *Holochain) AgentHash() (id Hash)

AgentHash returns the hash of the Agent entry

func (*Holochain) AgentTopHash

func (h *Holochain) AgentTopHash() (id Hash)

AgentHash returns the hash of the Agent entry

func (*Holochain) BSget

func (h *Holochain) BSget() (err error)

func (*Holochain) BSpost

func (h *Holochain) BSpost() (err error)

func (*Holochain) BridgeCall

func (h *Holochain) BridgeCall(zomeType string, function string, arguments interface{}, token string) (result interface{}, err error)

BridgeCall executes a function exposed through a bridge

func (*Holochain) BuildBridge

func (h *Holochain) BuildBridge(app *BridgeApp, port string) (err error)

BuildBridge creates the bridge structures on both sides assumes that GenChain has been called for both sides already

func (*Holochain) Call

func (h *Holochain) Call(zomeType string, function string, arguments interface{}, exposureContext string) (result interface{}, err error)

Call executes an exposed function

func (*Holochain) Chain

func (h *Holochain) Chain() (n *Chain)

func (*Holochain) Close

func (h *Holochain) Close()

Close releases the resources associated with a holochain

func (*Holochain) DBPath

func (h *Holochain) DBPath() string

DBPath returns a holochain DB path

func (*Holochain) DHT

func (h *Holochain) DHT() *DHT

DHT exposes the DHT structure

func (*Holochain) DNAHash

func (h *Holochain) DNAHash() (id Hash)

DNAHash returns the hash of the DNA entry which is also the holochain ID

func (*Holochain) DNAPath

func (h *Holochain) DNAPath() string

DNAPath returns a holochain DNA path

func (*Holochain) Debug

func (h *Holochain) Debug(m string)

func (*Holochain) Debugf

func (h *Holochain) Debugf(m string, args ...interface{})

Debugf sends a formatted string to the debug log

func (*Holochain) EncodeDNA

func (h *Holochain) EncodeDNA(writer io.Writer) (err error)

EncodeDNA encodes a holochain's DNA to an io.Writer

func (*Holochain) GenChain

func (h *Holochain) GenChain() (headerHash Hash, err error)

GenChain establishes a holochain instance by creating the initial genesis entries in the chain It assumes a properly set up .holochain sub-directory with a config file and keys for signing.

func (*Holochain) GetBridgeToken

func (h *Holochain) GetBridgeToken(hash Hash) (token string, url string, err error)

GetBridgeToken returns a token given the a hash

func (*Holochain) GetBridges

func (h *Holochain) GetBridges() (bridges []Bridge, err error)

GetBridges returns a list of the active bridges on the holochain

func (*Holochain) GetEntryDef

func (h *Holochain) GetEntryDef(t string) (zome *Zome, d *EntryDef, err error)

GetEntryDef returns an EntryDef of the given name @TODO this makes the incorrect assumption that entry type strings are unique across zomes

func (*Holochain) GetPrivateEntryDefs

func (h *Holochain) GetPrivateEntryDefs() (privateDefs []EntryDef)

func (*Holochain) GetProperty

func (h *Holochain) GetProperty(prop string) (property string, err error)

GetProperty returns the value of a DNA property

func (*Holochain) GetValidationResponse

func (h *Holochain) GetValidationResponse(a ValidatingAction, hash Hash) (resp ValidateResponse, err error)

GetValidationResponse check the validation request and builds the validation package based on the app's requirements

func (*Holochain) GetZome

func (h *Holochain) GetZome(zName string) (z *Zome, err error)

GetZome returns a zome structure given its name

func (*Holochain) HandleAsyncSends

func (h *Holochain) HandleAsyncSends() (err error)

HandleAsyncSends waits on a channel for asyncronous sends

func (*Holochain) HandlePeerFound

func (h *Holochain) HandlePeerFound(pi pstore.PeerInfo)

implement peer found function for mdns discovery

func (*Holochain) HashSpec

func (h *Holochain) HashSpec() HashSpec

HashSpec exposes the hashSpec structure

func (*Holochain) MakeRibosome

func (h *Holochain) MakeRibosome(t string) (r Ribosome, z *Zome, err error)

MakeRibosome creates a Ribosome object based on the zome type

func (*Holochain) Name

func (h *Holochain) Name() string

func (*Holochain) NewEntry

func (h *Holochain) NewEntry(now time.Time, entryType string, entry Entry) (hash Hash, header *Header, err error)

NewEntry adds an entry and it's header to the chain and returns the header and it's hash

func (*Holochain) Node

func (h *Holochain) Node() *Node

DHT exposes the Node structure

func (*Holochain) NodeIDStr

func (h *Holochain) NodeIDStr() string

NodeIDStr exposes the agent element

func (*Holochain) Nucleus

func (h *Holochain) Nucleus() (n *Nucleus)

func (*Holochain) Prepare

func (h *Holochain) Prepare() (err error)

Prepare sets up a holochain to run by: loading the schema validators, setting up a Network node and setting up the DHT

func (*Holochain) PrepareHashType

func (h *Holochain) PrepareHashType() (err error)

PrepareHashType makes sure the given string is a correct multi-hash and stores the code and length to the Holochain struct

func (*Holochain) Query

func (h *Holochain) Query(options *QueryOptions) (results []QueryResult, err error)

Query scans the local chain and returns a collection of results based on the options specified

func (*Holochain) Reset

func (h *Holochain) Reset() (err error)

Reset deletes all chain and dht data and resets data structures

func (*Holochain) RootPath

func (h *Holochain) RootPath() string

RootPath returns a holochain root path

func (*Holochain) Send

func (h *Holochain) Send(basectx context.Context, proto int, to peer.ID, message *Message, timeout time.Duration) (response interface{}, err error)

Send builds a message and either delivers it locally or over the network via node.Send

func (*Holochain) SendAsync

func (h *Holochain) SendAsync(proto int, to peer.ID, msg *Message, callback *Callback, timeout time.Duration) (err error)

SendAsync builds a message and either delivers it locally or over the network via node.Send but registers a function for asyncronous call back

func (*Holochain) Sign

func (h *Holochain) Sign(doc []byte) (sig []byte, err error)

Sign uses the agent' private key to sign the contents of doc

func (*Holochain) StartBackgroundTasks

func (h *Holochain) StartBackgroundTasks()

StartBackgroundTasks sets the various background processes in motion

func (*Holochain) Started

func (h *Holochain) Started() bool

Started returns true if the chain has been gened

func (*Holochain) TaskTicker

func (h *Holochain) TaskTicker(interval time.Duration, fn func(h *Holochain)) chan bool

TaskTicker creates a closure for a holochain task

func (*Holochain) TestPath

func (h *Holochain) TestPath() string

TestPath returns the path to a holochain's test directory

func (*Holochain) Top

func (h *Holochain) Top() (top Hash, err error)

Top returns a hash of top header or err if not yet defined

func (*Holochain) UIPath

func (h *Holochain) UIPath() string

UIPath returns a holochain UI path

func (*Holochain) ValidateAction

func (h *Holochain) ValidateAction(a ValidatingAction, entryType string, pkg *Package, sources []peer.ID) (def *EntryDef, err error)

ValidateAction runs the different phases of validating an action

func (*Holochain) VerifySignature

func (h *Holochain) VerifySignature(signature []byte, data string, pubKey ic.PubKey) (matches bool, err error)

VerifySignature uses the signature, data(doc) and signatory's public key to Verify the sign in contents of doc

func (*Holochain) Walk

func (h *Holochain) Walk(fn WalkerFn, entriesToo bool) (err error)

Walk takes the argument fn which must be WalkerFn Every WalkerFn is of the form: func(key *Hash, h *Header, entry interface{}) error

func (*Holochain) ZomePath

func (h *Holochain) ZomePath(z *Zome) string

ZomePath returns the path to the zome dna data @todo sanitize the name value

type JSONEntry

type JSONEntry struct {
	C interface{}
}

JSONEntry is a structure for implementing JSON encoding of Entry content

func (*JSONEntry) Content

func (e *JSONEntry) Content() interface{}

func (*JSONEntry) Marshal

func (e *JSONEntry) Marshal() (b []byte, err error)

func (*JSONEntry) Unmarshal

func (e *JSONEntry) Unmarshal(b []byte) (err error)

type JSONSchemaValidator

type JSONSchemaValidator struct {
	// contains filtered or unexported fields
}

func BuildJSONSchemaValidatorFromFile

func BuildJSONSchemaValidatorFromFile(path string) (validator *JSONSchemaValidator, err error)

func BuildJSONSchemaValidatorFromString

func BuildJSONSchemaValidatorFromString(input string) (validator *JSONSchemaValidator, err error)

func (*JSONSchemaValidator) Validate

func (v *JSONSchemaValidator) Validate(entry interface{}) (err error)

type JSRibosome

type JSRibosome struct {
	// contains filtered or unexported fields
}

JSRibosome holds data needed for the Javascript VM

func (*JSRibosome) BridgeGenesis

func (jsr *JSRibosome) BridgeGenesis(side int, dnaHash Hash, data string) (err error)

BridgeGenesis runs the bridging genesis function this function gets called on both sides of the bridging

func (*JSRibosome) Call

func (jsr *JSRibosome) Call(fn *FunctionDef, params interface{}) (result interface{}, err error)

Call calls the zygo function that was registered with expose

func (*JSRibosome) ChainGenesis

func (jsr *JSRibosome) ChainGenesis() (err error)

ChainGenesis runs the application genesis function this function gets called after the genesis entries are added to the chain

func (*JSRibosome) Receive

func (jsr *JSRibosome) Receive(from string, msg string) (response string, err error)

Receive calls the app receive function for node-to-node messages

func (*JSRibosome) Run

func (jsr *JSRibosome) Run(code string) (result interface{}, err error)

Run executes javascript code

func (*JSRibosome) RunAsyncSendResponse

func (jsr *JSRibosome) RunAsyncSendResponse(response AppMsg, callback string, callbackID string) (result interface{}, err error)

func (*JSRibosome) Type

func (jsr *JSRibosome) Type() string

Type returns the string value under which this ribosome is registered

func (*JSRibosome) ValidateAction

func (jsr *JSRibosome) ValidateAction(action Action, def *EntryDef, pkg *ValidationPackage, sources []string) (err error)

ValidateAction builds the correct validation function based on the action an calls it

func (*JSRibosome) ValidatePackagingRequest

func (jsr *JSRibosome) ValidatePackagingRequest(action ValidatingAction, def *EntryDef) (req PackagingReq, err error)

ValidatePackagingRequest calls the app for a validation packaging request for an action

type LibP2PAgent

type LibP2PAgent struct {
	// contains filtered or unexported fields
}

func (*LibP2PAgent) AgentEntry

func (a *LibP2PAgent) AgentEntry(revocation Revocation) (entry AgentEntry, err error)

func (*LibP2PAgent) AgentType

func (a *LibP2PAgent) AgentType() AgentType

func (*LibP2PAgent) GenKeys

func (a *LibP2PAgent) GenKeys(seed io.Reader) (err error)

func (*LibP2PAgent) Identity

func (a *LibP2PAgent) Identity() AgentIdentity

func (*LibP2PAgent) NodeID

func (a *LibP2PAgent) NodeID() (nodeID peer.ID, nodeIDStr string, err error)

func (*LibP2PAgent) PrivKey

func (a *LibP2PAgent) PrivKey() ic.PrivKey

func (*LibP2PAgent) PubKey

func (a *LibP2PAgent) PubKey() ic.PubKey

func (*LibP2PAgent) SetIdentity

func (a *LibP2PAgent) SetIdentity(id AgentIdentity)
type Link struct {
	LinkAction string // StatusAction (either AddAction or DelAction)
	Base       string // hash of entry (perhaps elsewhere) to which we are attaching the link
	Link       string // hash of entry being linked to
	Tag        string // tag
}

Link structure for holding meta tagging of linking entry

type LinkEvent

type LinkEvent struct {
	Status     int
	Source     string
	LinksEntry string
}

LinkEvent represents the value stored in buntDB associated with a link key for one source having stored one LinkingEntry (The Link struct defined in entry.go is encoded in the key used for buntDB)

type LinkQuery

type LinkQuery struct {
	Base       Hash
	T          string
	StatusMask int
}

LinkQuery holds a getLinks query

type LinkQueryResp

type LinkQueryResp struct {
	Links []TaggedHash
}

LinkQueryResp holds response to getLinks query

type LinkReq

type LinkReq struct {
	Base  Hash // data on which to attach the links
	Links Hash // hash of the source entry making the link, i.e. the req provenance
}

LinkReq holds a link request

type LinksEntry

type LinksEntry struct {
	Links []Link
}

LinksEntry holds one or more links

type ListAddReq

type ListAddReq struct {
	ListType    string
	Peers       []string
	WarrantType int
	Warrant     []byte
}

type Logger

type Logger struct {
	Name    string
	Enabled bool
	Format  string

	Prefix      string
	PrefixColor *color.Color
	// contains filtered or unexported fields
}

Logger holds logger configuration

func (*Logger) GetColor

func (h *Logger) GetColor(colorName string) *color.Color

func (*Logger) Log

func (l *Logger) Log(m interface{})

func (*Logger) Logf

func (l *Logger) Logf(m string, args ...interface{})

func (*Logger) New

func (l *Logger) New(w io.Writer) (err error)

func (*Logger) SetPrefix

func (l *Logger) SetPrefix(prefixFormat string)

type Loggers

type Loggers struct {
	App        Logger
	Debug      Logger
	DHT        Logger
	Gossip     Logger
	TestPassed Logger
	TestFailed Logger
	TestInfo   Logger
}

Loggers holds the logging structures for the different parts of the system

type Message

type Message struct {
	Type MsgType
	Time time.Time
	From peer.ID
	Body interface{}
}

Message represents data that can be sent to node in the network

func (*Message) Decode

func (m *Message) Decode(r io.Reader) (err error)

Decode converts a message from gob format @TODO generalize for other message encoding formats

func (*Message) Encode

func (m *Message) Encode() (data []byte, err error)

Encode codes a message to gob format @TODO generalize for other message encoding formats

func (*Message) Fingerprint

func (m *Message) Fingerprint() (f Hash, err error)

Fingerprint creates a hash of a message

func (Message) String

func (m Message) String() string

String converts a message to a nice string

type Meta

type Meta struct {
	H Hash   // hash of link-data associated
	T string // meta-data type identifier
	V []byte // meta-data
}

Meta holds data that can be associated with a hash @todo, we should also be storing the meta-data source

type ModAgentOptions

type ModAgentOptions struct {
	Identity   string
	Revocation string
}

type ModReq

type ModReq struct {
	H Hash
	N Hash
}

ModReq holds the data of a mod request

type MsgType

type MsgType int8
const (
	ERROR_RESPONSE MsgType = iota
	OK_RESPONSE

	PUT_REQUEST
	DEL_REQUEST
	MOD_REQUEST
	GET_REQUEST
	LINK_REQUEST
	GETLINK_REQUEST
	DELETELINK_REQUEST

	GOSSIP_REQUEST

	VALIDATE_PUT_REQUEST
	VALIDATE_LINK_REQUEST
	VALIDATE_DEL_REQUEST
	VALIDATE_MOD_REQUEST

	APP_MESSAGE

	LISTADD_REQUEST

	FIND_NODE_REQUEST
)

func (MsgType) String

func (msgType MsgType) String() string

type Node

type Node struct {
	HashAddr peer.ID
	NetAddr  ma.Multiaddr
	// contains filtered or unexported fields
}

Node represents a node in the network

func NewNode

func NewNode(listenAddr string, protoMux string, agent *LibP2PAgent, enableNATUPnP bool, log *Logger) (node *Node, err error)

NewNode creates a new node with given multiAddress listener string and identity

func (*Node) Block

func (node *Node) Block(addr peer.ID)

Block adds a peer to the blocklist

func (*Node) Close

func (node *Node) Close() error

Close shuts down the node

func (*Node) Context

func (node *Node) Context() context.Context

Context return node's context

func (*Node) Distance

func (node *Node) Distance(id peer.ID) *big.Int

Distance returns the nodes peer distance to another node for purposes of gossip

func (*Node) EnableMDNSDiscovery

func (n *Node) EnableMDNSDiscovery(h *Holochain, interval time.Duration) (err error)

func (*Node) ExternalAddr

func (n *Node) ExternalAddr() ma.Multiaddr

func (*Node) FindLocal

func (node *Node) FindLocal(id peer.ID) pstore.PeerInfo

FindLocal looks for a peer with a given ID connected to this node and returns its peer info

func (*Node) FindPeer

func (node *Node) FindPeer(ctx context.Context, id peer.ID) (pstore.PeerInfo, error)

FindPeer searches for a peer with given ID. it is also an implementation the FindPeer() method of the RoutedHost interface in go-libp2p/p2p/host/routed and makes the Node object the "Router"

func (*Node) GetClosestPeers

func (node *Node) GetClosestPeers(ctx context.Context, key Hash) (<-chan peer.ID, error)

Kademlia 'node lookup' operation. Returns a channel of the K closest peers to the given key

func (*Node) InitBlockedList

func (node *Node) InitBlockedList(list PeerList)

InitBlockedList sets up the blockedlist from a PeerList

func (*Node) IsBlocked

func (node *Node) IsBlocked(addr peer.ID) (ok bool)

IsBlockedListed checks to see if a node is on the blockedlist

func (*Node) NewMessage

func (node *Node) NewMessage(t MsgType, body interface{}) (msg *Message)

NewMessage creates a message from the node with a new current timestamp

func (*Node) Process

func (node *Node) Process() goprocess.Process

Process return node's process

func (*Node) Send

func (node *Node) Send(ctx context.Context, proto int, addr peer.ID, m *Message) (response Message, err error)

Send delivers a message to a node via the given protocol

func (*Node) StartProtocol

func (node *Node) StartProtocol(h *Holochain, proto int) (err error)

StartProtocol initiates listening for a protocol on the node

func (*Node) Unblock

func (node *Node) Unblock(addr peer.ID)

Unblock removes a peer from the blocklist

type Nucleus

type Nucleus struct {
	// contains filtered or unexported fields
}

Nucleus encapsulates Application parts: Ribosomes to run code in Zomes, plus application validation and direct message passing protocols

func NewNucleus

func NewNucleus(h *Holochain, dna *DNA) *Nucleus

NewNucleus creates a new Nucleus structure

func (*Nucleus) DNA

func (n *Nucleus) DNA() (dna *DNA)

func (*Nucleus) RunGenesis

func (n *Nucleus) RunGenesis() (err error)

func (*Nucleus) Start

func (n *Nucleus) Start() (err error)

type Package

type Package struct {
	Chain []byte
}

Package holds app specified data needed for validation (wire package)

func MakePackage

func MakePackage(h *Holochain, req PackagingReq) (pkg Package, err error)

MakePackage converts a package request into a package, loading chain data as necessary this is the package that gets sent over the wire. Chain DNA is omitted in this package because it can be added at the destination and the chain will still validate.

type PackagingReq

type PackagingReq map[string]interface{}

PackagingReq holds a request from an app for data to be included in the validation response

type PeerInfo

type PeerInfo struct {
	ID    []byte   // byte version peer.ID
	Addrs [][]byte // byte version of multiaddrs
}

an encodable version of pstore.PeerInfo which gob doesn't like also libp2p encodes other stuff like connection type into this which we may have to do too.

type PeerList

type PeerList struct {
	Type    PeerListType
	Records []PeerRecord
}

type PeerListType

type PeerListType string

we also gossip about peers too, keeping lists of different peers e.g. blockedlist etc

type PeerRecord

type PeerRecord struct {
	ID      peer.ID
	Warrant string // evidence, reasons, documentation of why peer is in this list
}

type Progenitor

type Progenitor struct {
	Identity string
	PubKey   []byte
}

Progenitor holds data on the creator of the DNA

type Protocol

type Protocol struct {
	ID       protocol.ID
	Receiver ReceiverFn
}

Protocol encapsulates data for our different protocols

type Put

type Put struct {
	Idx int
	M   Message
}

Put holds a put or link for gossiping

type PutReq

type PutReq struct {
	H Hash
	S int
	D interface{}
}

PutReq holds the data of a put request

type QueryConstrain

type QueryConstrain struct {
	EntryTypes []string
	Contains   string
	Equals     string
	Matches    string
	Count      int
	Page       int
}

type QueryOptions

type QueryOptions struct {
	Return    QueryReturn
	Constrain QueryConstrain
	Order     QueryOrder
}

type QueryOrder

type QueryOrder struct {
	Ascending bool
}

type QueryResult

type QueryResult struct {
	Header *Header
	Entry  Entry
}

type QueryReturn

type QueryReturn struct {
	Hashes  bool
	Entries bool
	Headers bool
}

type ReceiverFn

type ReceiverFn func(h *Holochain, m *Message) (response interface{}, err error)

type Revocation

type Revocation interface {
	Verify() error
	Marshal() ([]byte, error)
	Unmarshal([]byte) error
}

type Ribosome

type Ribosome interface {
	Type() string
	ValidateAction(action Action, def *EntryDef, pkg *ValidationPackage, sources []string) (err error)
	ValidatePackagingRequest(action ValidatingAction, def *EntryDef) (req PackagingReq, err error)
	ChainGenesis() error
	BridgeGenesis(side int, dnaHash Hash, data string) error
	Receive(from string, msg string) (response string, err error)
	Call(fn *FunctionDef, params interface{}) (interface{}, error)
	Run(code string) (result interface{}, err error)
	RunAsyncSendResponse(response AppMsg, callback string, callbackID string) (result interface{}, err error)
}

Ribosome type abstracts the functions of code execution environments

func CreateRibosome

func CreateRibosome(h *Holochain, zome *Zome) (Ribosome, error)

CreateRibosome returns a new Ribosome of the given type

func NewJSRibosome

func NewJSRibosome(h *Holochain, zome *Zome) (n Ribosome, err error)

NewJSRibosome factory function to build a javascript execution environment for a zome

func NewZygoRibosome

func NewZygoRibosome(h *Holochain, zome *Zome) (n Ribosome, err error)

NewZygoRibosome factory function to build a zygo execution environment for a zome

type RibosomeFactory

type RibosomeFactory func(h *Holochain, zome *Zome) (Ribosome, error)

type RoutingTable

type RoutingTable struct {

	// kBuckets define all the fingers to other nodes.
	Buckets []*Bucket

	// notification functions
	PeerRemoved func(peer.ID)
	PeerAdded   func(peer.ID)
	// contains filtered or unexported fields
}

RoutingTable defines the routing table.

func NewRoutingTable

func NewRoutingTable(bucketsize int, localID peer.ID, latency time.Duration, m pstore.Metrics) *RoutingTable

NewRoutingTable creates a new routing table with a given bucketsize, local ID, and latency tolerance.

func (*RoutingTable) Find

func (rt *RoutingTable) Find(id peer.ID) peer.ID

Find a specific peer by ID or return nil

func (*RoutingTable) IsEmpty

func (rt *RoutingTable) IsEmpty() (empty bool)

IsEmpty returns bool

func (*RoutingTable) ListPeers

func (rt *RoutingTable) ListPeers() []peer.ID

ListPeers takes a RoutingTable and returns a list of all peers from all buckets in the table. NOTE: This is potentially unsafe... use at your own risk

func (*RoutingTable) NearestPeer

func (rt *RoutingTable) NearestPeer(hash Hash) peer.ID

NearestPeer returns a single peer that is nearest to the given Hash

func (*RoutingTable) NearestPeers

func (rt *RoutingTable) NearestPeers(hash Hash, count int) []peer.ID

NearestPeers returns a list of the 'count' closest peers to the given ID

func (*RoutingTable) Print

func (rt *RoutingTable) Print()

Print prints a descriptive statement about the provided RoutingTable

func (*RoutingTable) Remove

func (rt *RoutingTable) Remove(p peer.ID)

Remove deletes a peer from the routing table. This is to be used when we are sure a node has disconnected completely.

func (*RoutingTable) Size

func (rt *RoutingTable) Size() int

Size returns the total number of peers in the routing table

func (*RoutingTable) Update

func (rt *RoutingTable) Update(p peer.ID)

Update adds or moves the given peer to the front of its respective bucket If a peer gets removed from a bucket, it is returned

type SchemaValidator

type SchemaValidator interface {
	Validate(interface{}) error
}

SchemaValidator interface for schema validation

type SelfRevocation

type SelfRevocation struct {
	Data   []byte // concatination of key length, two marshaled keys, and revocation properties
	OldSig []byte // signature of oldnew by old key
	NewSig []byte // signature by oldnew new key
}

SelfRevocation holds the old key being revoked and the new key, other revocation data and the two cryptographic signatures of that data by the two keys to confirm the revocation

func NewSelfRevocation

func NewSelfRevocation(old, new ic.PrivKey, payload []byte) (rP *SelfRevocation, err error)

func (*SelfRevocation) Marshal

func (r *SelfRevocation) Marshal() (data []byte, err error)

func (*SelfRevocation) Unmarshal

func (r *SelfRevocation) Unmarshal(data []byte) (err error)

func (*SelfRevocation) Verify

func (r *SelfRevocation) Verify() (err error)

Verify confirms that a self-revocation is properly signed

type SelfRevocationWarrant

type SelfRevocationWarrant struct {
	Revocation SelfRevocation
}

SelfRevocationWarrant warrants that the first party revoked its own key in favor of the second

func NewSelfRevocationWarrant

func NewSelfRevocationWarrant(revocation *SelfRevocation) (wP *SelfRevocationWarrant, err error)

func (*SelfRevocationWarrant) Decode

func (w *SelfRevocationWarrant) Decode(data []byte) (err error)

func (*SelfRevocationWarrant) Encode

func (w *SelfRevocationWarrant) Encode() (data []byte, err error)

func (*SelfRevocationWarrant) Parties

func (w *SelfRevocationWarrant) Parties() (parties []Hash, err error)

func (*SelfRevocationWarrant) Property

func (w *SelfRevocationWarrant) Property(key string) (value interface{}, err error)

func (*SelfRevocationWarrant) Type

func (w *SelfRevocationWarrant) Type() int

func (*SelfRevocationWarrant) Verify

func (w *SelfRevocationWarrant) Verify(h *Holochain) (err error)

type SendOptions

type SendOptions struct {
	Callback *Callback
	Timeout  int
}

type Service

type Service struct {
	Settings     ServiceConfig
	DefaultAgent Agent
	Path         string
}

A Service is a Holochain service data structure

func Init

func Init(root string, identity AgentIdentity, seed io.Reader) (service *Service, err error)

Init initializes service defaults including a signing key pair for an agent and writes them out to configuration files in the root path (making the directory if necessary)

func LoadService

func LoadService(path string) (service *Service, err error)

LoadService creates a service object from a configuration file

func SetupTestService

func SetupTestService() (d string, s *Service)

func (*Service) Clone

func (s *Service) Clone(srcPath string, root string, agent Agent, new bool, initDB bool) (hP *Holochain, err error)

Clone copies DNA files from a source directory bool new indicates if this clone should create a new DNA (when true) or act as a Join

func (*Service) ConfiguredChains

func (s *Service) ConfiguredChains() (chains map[string]*Holochain, err error)

ConfiguredChains returns a list of the configured chains for the given service

func (*Service) GenChain

func (s *Service) GenChain(name string) (h *Holochain, err error)

GenChain adds the genesis entries to a newly cloned or joined chain

func (*Service) InitAppDir

func (service *Service) InitAppDir(root string, encodingFormat string) (err error)

func (*Service) IsConfigured

func (s *Service) IsConfigured(name string) (f string, err error)

IsConfigured checks a directory for correctly set up holochain configuration file

func (*Service) ListChains

func (s *Service) ListChains() (list string)

List chains produces a textual representation of the chains in the .holochain directory

func (*Service) Load

func (s *Service) Load(name string) (h *Holochain, err error)

Load instantiates a Holochain instance from disk

func (*Service) MakeAppPackage

func (service *Service) MakeAppPackage(h *Holochain) (data []byte, err error)

MakeAppPackage creates a package blob from a given holochain

func (*Service) MakeTestingApp

func (s *Service) MakeTestingApp(root string, encodingFormat string, initDB bool, newUUID bool, agent Agent) (h *Holochain, err error)

MakeTestingApp generates a holochain used for testing purposes

func (*Service) SaveFromAppPackage

func (service *Service) SaveFromAppPackage(reader io.Reader, path string, name string, agent Agent, decodingFormat string, encodingFormat string, newUUID bool) (appPackage *AppPackage, err error)

SaveFromAppPackage writes out a holochain application based on appPackage file to path

type ServiceConfig

type ServiceConfig struct {
	DefaultPeerModeAuthor  bool
	DefaultPeerModeDHTNode bool
	DefaultBootstrapServer string
	DefaultEnableMDNS      bool
	DefaultEnableNATUPnP   bool
}

ServiceConfig holds the service settings

func (*ServiceConfig) Validate

func (c *ServiceConfig) Validate() (err error)

Validate validates settings values

type Signature

type Signature struct {
	S []byte
}

type StatusChange

type StatusChange struct {
	Action string // either AddAction, ModAction, or DelAction
	Hash   Hash
}

StatusChange records change of status of an entry in the header

type TaggedHash

type TaggedHash struct {
	H         string // the hash of the link; gets filled by dht base node when answering get link request
	E         string // the value of link, gets filled if options set Load to true
	EntryType string // the entry type of the link, gets filled if options set Load to true
	T         string // the tag of the link, gets filled only if a tag wasn't specified and all tags are being returns
	Source    string // the statuses on the link, gets filled if options set Load to true
}

TaggedHash holds associated entries for the LinkQueryResponse

type TestConfig

type TestConfig struct {
	GossipInterval int // interval in milliseconds between gossips
	Duration       int // if non-zero number of seconds to keep all nodes alive
	Clone          []CloneSpec
}

TestConfig holds the configuration options for a test

func LoadTestConfig

func LoadTestConfig(dir string) (config *TestConfig, err error)

LoadTestConfig unmarshals test json data

type TestData

type TestData struct {
	Convey   string        // a human readable description of the tests intent
	Zome     string        // the zome in which to find the function
	FnName   string        // the function to call
	Input    interface{}   // the function's input
	Output   interface{}   // the expected output to match against (full match)
	Err      string        // the expected error to match against
	Regexp   string        // the expected out to match again (regular expression)
	Time     time.Duration // offset in milliseconds from the start of the test at which to run this test.
	Wait     time.Duration // time in milliseconds to wait before running this test from when the previous ran
	Exposure string        // the exposure context for the test call (defaults to ZOME_EXPOSURE)
	Raw      bool          // set to true if we should ignore fnName and just call input as raw code in the zome, useful for testing helper functions and validation functions
	Repeat   int           // number of times to repeat this test, useful for scenario testing
}

TestData holds a test entry for a chain

type TestFixtures

type TestFixtures struct {
	Agents []AgentFixture
}

TestFixtures defines data needed to run tests

type TestSet

type TestSet struct {
	Tests    []TestData
	Identity string
	Fixtures TestFixtures
}

TestSet holds a set of tests plus configuration and fixture data for those tests

func LoadTestFile

func LoadTestFile(dir string, file string) (tests TestSet, err error)

LoadTestFile unmarshals test json data

type ValidateQuery

type ValidateQuery struct {
	H Hash
}

ValidateQuery holds the data from a validation query on the Source protocol

type ValidateResponse

type ValidateResponse struct {
	Type    string
	Header  Header
	Entry   GobEntry
	Package Package
}

ValidateResponse holds the response to committing validates (PUT/MOD/DEL)

type ValidatingAction

type ValidatingAction interface {
	Name() string
	Do(h *Holochain) (response interface{}, err error)
	SysValidation(h *Holochain, def *EntryDef, pkg *Package, sources []peer.ID) (err error)
	Receive(dht *DHT, msg *Message, retries int) (response interface{}, err error)
	CheckValidationRequest(def *EntryDef) (err error)
	Args() []Arg
}

ValidatingAction provides an abstraction for grouping all the actions that participate in validation loop

type ValidationPackage

type ValidationPackage struct {
	Chain *Chain
}

ValidationPackage holds app specified data needed for validation. This version holds the package with any chain data un-marshaled after validation for passing into the app for app level validation

func MakeValidationPackage

func MakeValidationPackage(h *Holochain, pkg *Package) (vpkg *ValidationPackage, err error)

MakeValidationPackage converts a received Package into a ValidationPackage and validates any chain data that was included

type WalkerFn

type WalkerFn func(key *Hash, header *Header, entry Entry) error

WalkerFn a function type for call Walk

type Warrant

type Warrant interface {

	// Int returns the warrant type
	Type() int

	// Parties returns the hashes of the public keys of the signers of the warrant
	Parties() ([]Hash, error)

	// Verify confirms that the content of a warrant is valid and has been signed by the
	// the parties in it.  Requires a Holochain object for context, returns nil if it
	// verfies or an error
	Verify(h *Holochain) error

	// Property returns a value of a property attested to by the warrant
	// returns a WarrantPropertyNotFoundErr if the warrant doesn't have that property
	Property(key string) (value interface{}, err error)

	// Encode marshals the warrant into bytes for sending over the wire
	Encode() (data []byte, err error)

	// Decode unmarshals a warrant from bytes
	Decode(data []byte) (err error)
}

Warrant abstracts the notion of a multi-party cryptographically verifiable signed claim the meaning of the warrant is understood by the warrant name an/or by properties contained in it

func DecodeWarrant

func DecodeWarrant(warrantType int, data []byte) (w Warrant, err error)

type Zome

type Zome struct {
	Name         string
	Description  string
	Code         string
	Entries      []EntryDef
	RibosomeType string
	Functions    []FunctionDef
	BridgeFuncs  []string // functions in zome that can be bridged to by fromApp
	BridgeTo     Hash     // dna Hash of toApp that this zome is a client of
}

Zome struct encapsulates logically related code, from a "chromosome"

func (*Zome) CodeFileName

func (zome *Zome) CodeFileName() string

func (*Zome) GetEntryDef

func (z *Zome) GetEntryDef(entryName string) (e *EntryDef, err error)

GetEntryDef returns the entry def structure

func (*Zome) GetFunctionDef

func (zome *Zome) GetFunctionDef(fnName string) (fn *FunctionDef, err error)

GetFunctionDef returns the exposed function spec for the given zome and function

func (*Zome) GetPrivateEntryDefs

func (z *Zome) GetPrivateEntryDefs() (privateDefs []EntryDef)

func (*Zome) MakeRibosome

func (zome *Zome) MakeRibosome(h *Holochain) (r Ribosome, err error)

type ZomeFile

type ZomeFile struct {
	Name         string
	Description  string
	CodeFile     string
	Entries      []EntryDefFile
	RibosomeType string
	Functions    []FunctionDef
	BridgeFuncs  []string // functions in zome that can be bridged to by fromApp
	BridgeTo     string   // dna Hash of toApp that this zome is a client of
}

type ZygoRibosome

type ZygoRibosome struct {
	// contains filtered or unexported fields
}

ZygoRibosome holds data needed for the Zygo VM

func (*ZygoRibosome) BridgeGenesis

func (z *ZygoRibosome) BridgeGenesis(side int, dnaHash Hash, data string) (err error)

BridgeGenesis runs the bridging genesis function this function gets called on both sides of the bridging

func (*ZygoRibosome) Call

func (z *ZygoRibosome) Call(fn *FunctionDef, params interface{}) (result interface{}, err error)

Call calls the zygo function that was registered with expose

func (*ZygoRibosome) ChainGenesis

func (z *ZygoRibosome) ChainGenesis() (err error)

ChainGenesis runs the application genesis function this function gets called after the genesis entries are added to the chain

func (*ZygoRibosome) Receive

func (z *ZygoRibosome) Receive(from string, msg string) (response string, err error)

Receive calls the app receive function for node-to-node messages

func (*ZygoRibosome) Run

func (z *ZygoRibosome) Run(code string) (result interface{}, err error)

Run executes zygo code

func (*ZygoRibosome) RunAsyncSendResponse

func (z *ZygoRibosome) RunAsyncSendResponse(response AppMsg, callback string, callbackID string) (result interface{}, err error)

func (*ZygoRibosome) Type

func (z *ZygoRibosome) Type() string

Type returns the string value under which this ribosome is registered

func (*ZygoRibosome) ValidateAction

func (z *ZygoRibosome) ValidateAction(action Action, def *EntryDef, pkg *ValidationPackage, sources []string) (err error)

ValidateAction builds the correct validation function based on the action an calls it

func (*ZygoRibosome) ValidatePackagingRequest

func (z *ZygoRibosome) ValidatePackagingRequest(action ValidatingAction, def *EntryDef) (req PackagingReq, err error)

ValidatePackagingRequest calls the app for a validation packaging request for an action

Directories

Path Synopsis
cmd
bs
hcd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL