holochain

package module
v0.1.0-alpha-26 Latest Latest
Warning

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

Go to latest
Published: Jun 13, 2018 License: GPL-3.0 Imports: 61 Imported by: 9

README

Holochain

Code Status Travis Codecov Go Report Card 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. Alpha 1 was released May 2018.

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
Unix

(Unix includes macOS and Linux.)

  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. Setup your path (Almost all installation problems that have been reported stem from skipping this step.)

    • Export the $GOPATH variable in your shell profile.
    • 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"
  1. Install the command line tool suite with:
$ go get -d -v github.com/holochain/holochain-proto
$ cd $GOPATH/src/github.com/holochain/holochain-proto
$ make
  1. Test that it works (should look something like this):
$ hcadmin -v
hcadmin version 0.0.x (holochain y)
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
    
  3. Pull our holochain image from docker hub:

    	$ docker pull holochain/holochain-proto:develop
    
  4. To run holochain in your new environment, suitable to continue the walkthrough below in usage

    	$ docker run --rm -it --name clutter -p 3141:3141 holochain/holochain-proto:develop
    
  5. 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 allows interface developers lots 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 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 docs 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 HCDEBUG environment variable to 0 or 1 to temporarily override your settings to turn everything on or off. See also the Environment Variable documentation for more granular logging control.

Architecture Overview and Documentation

Architecture information and application developer documentation is in our developer.holochain.org.

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

Holochain Core Development

We accept Pull Requests and welcome your participation. Please make sure to include the issue number your branch names and use descriptive commit messages.

In Progress

Some helpful links:

Current Throughput graph:

Throughput Graph

Contribute

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

Getting started

Once you have followed the basic "getting started" guide above you will have the CLI tools installed locally.

All the commands (hcadmin, hcd, hcdev, etc.) are built from the same repo:

$ cd $GOPATH/src/github.com/holochain/holochain-proto

Go will throw errors complaining about not being on the $GOPATH if you try to run make from a separate copy of the holochain-proto repository. If you want to contribute to Holochain core you must work in the repository created by Go.

The Makefile contains all the build commands for Holochain. If you make an update to a command you will need to rebuild it before the changes take effect at the command line.

E.g. After making an update to cmd/hcdev/hcdev.go run $ make hcdev then run $ hcdev as normal.

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.

The package manager rewrites files that are tracked by git to configure imports. Be careful not to commit the generated imports to git!

make work adds the imports to the repository and make pub reverts them.

Every make command should automatically add and remove imports for you. If a make command is leaving mess behind in the repo, please open a bug report.

If you want to use go commands directly (e.g. go test) then you need to run make work manually first and remember to make pub before committing any changes.

Tests

To compile and run all the tests:

$ cd $GOPATH/src/github.com/holochain/holochain-proto
$ make test

go test can be used instead of make test, but only after make work.

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-2018, The MetaCurrency Project (Eric Harris-Braun, Arthur Brock, et. al.) Use of this source code is governed by GPLv3 found in the LICENSE file ----------------------------------------------------------------------------------------

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

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

Copyright (C) 2013-2018, 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/holochain/holochain-proto/tree/master/cmd/hc

For information not found here see the wiki:

https://github.com/holochain/holochain-proto/wiki

or the repo:

https://github.com/holochain/holochain-proto

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 (
	ValidationFailureBadPublicKeyFormat  = "bad public key format"
	ValidationFailureBadRevocationFormat = "bad revocation format"
)
View Source
const (
	ChainMarshalFlagsNone            = 0x00
	ChainMarshalFlagsNoHeaders       = 0x01
	ChainMarshalFlagsNoEntries       = 0x02
	ChainMarshalFlagsOmitDNA         = 0x04
	ChainMarshalFlagsNoPrivate       = 0x08
	ChainMarshalPrivateEntryRedacted = "%%PRIVATE ENTRY REDACTED%%"
)
View Source
const (
	GossipWithQueueSize = 10
	GossipPutQueueSize  = 1000
)
View Source
const (
	SysEntryTypePrefix     = "%"
	VirtualEntryTypePrefix = "%%"

	DataFormatJSON    = "json"
	DataFormatString  = "string"
	DataFormatRawJS   = "js"
	DataFormatRawZygo = "zygo"

	Public  = "public"
	Partial = "partial"
	Private = "private"
)
View Source
const (
	AgentEntryType   = SysEntryTypePrefix + "agent"
	AgentEntrySchema = `` /* 651-byte string literal not displayed */

)
View Source
const (
	DelEntryType   = SysEntryTypePrefix + "del"
	DelEntrySchema = `` /* 466-byte string literal not displayed */

)
View Source
const (
	DNAEntryType     = SysEntryTypePrefix + "dna"
	DataFormatSysDNA = "_DNA"
)
View Source
const (
	// virtual entry type, not actually on the chain
	KeyEntryType = VirtualEntryTypePrefix + "key"

	DataFormatSysKey = "_key"
)
View Source
const (
	MigrateEntryType = SysEntryTypePrefix + "migrate"
	// currently both to/from have the same schema
	MigrateEntrySchema = `` /* 731-byte string literal not displayed */

	// Type can only be one of two things... open or close
	MigrateEntryTypeClose = "close"
	MigrateEntryTypeOpen  = "open"
)
View Source
const (
	// Version is the numeric version number of the holochain library
	Version int = 26

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

	// DefaultSendTimeout a time.Duration to wait by default for send to complete
	DefaultSendTimeout = 3000 * time.Millisecond
)
View Source
const (
	AddLinkAction = ""
	DelLinkAction = "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 (
	ReceiptOK = iota
	ReceiptRejected
)
View Source
const (
	JSRibosomeType = "js"

	ErrHandlingReturnErrorsStr = "returnErrorValue"
	ErrHandlingThrowErrorsStr  = "throwErrors"
)
View Source
const (
	RetryingStopper = iota
	GossipingStopper
	BootstrappingStopper
	RefreshingStopper
	HoldingStopper
)
View Source
const (
	ActionProtocol = iota
	ValidateProtocol
	GossipProtocol
	KademliaProtocol
)
View Source
const (
	PeerTTL                       = time.Minute * 10
	DefaultRoutingRefreshInterval = time.Minute
	DefaultGossipInterval         = time.Second * 2
	DefaultHoldingCheckInterval   = time.Second * 30
)
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"

	BridgeCaller    = 0
	BridgeCallee    = 1
	BridgeCallerStr = "0"
	BridgeCalleeStr = "1"

	BundleCancelReasonUserCancel = "userCancel"
	BundleCancelReasonTimeout    = "timeout"

	BundleCancelResponseOK     = ""
	BundleCancelResponseCommit = "commit"

	ValidationFailedErrMsg = "Validation Failed"
)
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"

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

	DefaultHashType HashType = HashType("sha2-256") // default hashing algo if not provided in DNA

	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 (
	DataFormatLinks = "links"
)
View Source
const (
	DefaultBundleTimeout = 5000
)
View Source
const (
	DefaultRetryInterval = time.Millisecond * 500
)
View Source
const (
	GossipBackPutDelay = 100 * time.Millisecond
)
View Source
const (
	HeadersEntrySchema = `` /* 2953-byte string literal not displayed */

)
View Source
const (
	HeadersEntryType = SysEntryTypePrefix + "header"
)
View Source
const (
	HolochainErrorPrefix = "HolochainError"
)
View Source
const (
	JSLibrary = `var HC={Version:` + `"` + VersionStr + "\"" +
		`SysEntryType:{` +
		`DNA:"` + DNAEntryType + `",` +
		`Agent:"` + AgentEntryType + `",` +
		`Key:"` + KeyEntryType + `",` +
		`Headers:"` + HeadersEntryType + `"` +
		`Del:"` + DelEntryType + `"` +
		`Migrate:"` + MigrateEntryType + `"` +
		`}` +
		`HashNotFound:null` +
		`,Status:{Live:` + StatusLiveVal +
		`,Rejected:` + StatusRejectedVal +
		`,Deleted:` + StatusDeletedVal +
		`,Modified:` + StatusModifiedVal +
		`,Any:` + StatusAnyVal +
		"}" +
		`,GetMask:{Default:` + GetMaskDefaultStr +
		`,Entry:` + GetMaskEntryStr +
		`,EntryType:` + GetMaskEntryTypeStr +
		`,Sources:` + GetMaskSourcesStr +
		`,All:` + GetMaskAllStr +
		"}" +
		`,LinkAction:{Add:"` + AddLinkAction + `",Del:"` + DelLinkAction + `"}` +
		`,PkgReq:{Chain:"` + PkgReqChain + `"` +
		`,ChainOpt:{None:` + PkgReqChainOptNoneStr +
		`,Headers:` + PkgReqChainOptHeadersStr +
		`,Entries:` + PkgReqChainOptEntriesStr +
		`,Full:` + PkgReqChainOptFullStr +
		"}" +
		"}" +
		`,Bridge:{Caller:` + BridgeCallerStr +
		`,Callee:` + BridgeCalleeStr +
		"}" +
		`,BundleCancel:{` +
		`Reason:{UserCancel:"` + BundleCancelReasonUserCancel +
		`",Timeout:"` + BundleCancelReasonTimeout +
		`"},Response:{OK:"` + BundleCancelResponseOK +
		`",Commit:"` + BundleCancelResponseCommit +
		`"}}` +
		`Migrate:{Close:"` + MigrateEntryTypeClose + `",Open:"` + MigrateEntryTypeOpen + `"}` +
		`};`
)
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_HashNotFound nil)` +
		`(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_Caller ` + BridgeCallerStr + ")" +
		`(def HC_Bridge_Callee ` + BridgeCalleeStr + ")" +

		`(def HC_LinkAction_Add "` + AddLinkAction + "\")" +
		`(def HC_LinkAction_Del "` + DelLinkAction + "\")" +
		`(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 + "\")" +

		`(def HC_Migrate_Close "` + MigrateEntryTypeClose + `")` +
		`(def HC_Migrate_Open "` + MigrateEntryTypeOpen + `")`
)

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: DataFormatJSON, Sharing: Public, Schema: AgentEntrySchema}
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\": [\"content\", \"timestamp\"]\n}"
        }
      ],

      # 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.
        },
        {
          "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.
        },
        {
          "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": "/*******************************************************************************\n * Utility functions\n ******************************************************************************/\n\n/**\n * Is this a valid entry type?\n *\n * @param {any} entryType The data to validate as an expected entryType.\n * @return {boolean} true if the passed argument is a valid entryType.\n */\nfunction isValidEntryType (entryType) {\n  // Add additonal entry types here as they are added to dna.json.\n  return [\"sampleEntry\"].includes(entryType);\n}\n\n/**\n * Returns the creator of an entity, given an entity hash.\n *\n * @param  {string} hash The entity hash.\n * @return {string} The agent hash of the entity creator.\n */\nfunction getCreator (hash) {\n  return get(hash, { GetMask: HC.GetMask.Sources })[0];\n}\n\n/*******************************************************************************\n * Required callbacks\n ******************************************************************************/\n\n/**\n * System genesis callback: Can the app start?\n *\n * Executes just after the initial genesis entries are committed to your chain\n * (1st - DNA entry, 2nd Identity entry). Enables you specify any additional\n * operations you want performed when a node joins your holochain.\n *\n * @return {boolean} true if genesis is successful and so the app may start.\n *\n * @see https://developer.holochain.org/API#genesis\n */\nfunction genesis () {\n  return true;\n}\n\n/**\n * Validation callback: Can this entry be committed to a source chain?\n *\n * @param  {string} entryType Type of the entry as per DNA config for this zome.\n * @param  {string|object} entry Data with type as per DNA config for this zome.\n * @param  {Header-object} header Header object for this entry.\n * @param  {Package-object|null} pkg Package object for this entry, if exists.\n * @param  {string[]} sources Array of agent hashes involved in this commit.\n * @return {boolean} true if this entry may be committed to a source chain.\n *\n * @see https://developer.holochain.org/API#validateCommit_entryType_entry_header_package_sources\n * @see https://developer.holochain.org/Validation_Functions\n */\nfunction validateCommit (entryType, entry, header, pkg, sources) {\n  return isValidEntryType(entryType);\n}\n\n/**\n * Validation callback: Can this entry be committed to the DHT on any node?\n *\n * It is very likely that this validation routine should check the same data\n * integrity as validateCommit, but, as it happens during a different part of\n * the data life-cycle, it may require additional validation steps.\n *\n * This function will only get called on entry types with \"public\" sharing, as\n * they are the only types that get put to the DHT by the system.\n *\n * @param  {string} entryType Type of the entry as per DNA config for this zome.\n * @param  {string|object} entry Data with type as per DNA config for this zome.\n * @param  {Header-object} header Header object for this entry.\n * @param  {Package-object|null} pkg Package object for this entry, if exists.\n * @param  {string[]} sources Array of agent hashes involved in this commit.\n * @return {boolean} true if this entry may be committed to the DHT.\n *\n * @see https://developer.holochain.org/API#validatePut_entryType_entry_header_package_sources\n * @see https://developer.holochain.org/Validation_Functions\n */\nfunction validatePut (entryType, entry, header, pkg, sources) {\n  return validateCommit(entryType, entry, header, pkg, sources);\n}\n\n/**\n * Validation callback: Can this entry be modified?\n *\n * Validate that this entry can replace 'replaces' due to 'mod'.\n *\n * @param  {string} entryType Type of the entry as per DNA config for this zome.\n * @param  {string|object} entry Data with type as per DNA config for this zome.\n * @param  {Header-object} header Header object for this entry.\n * @param  {string} replaces The hash string of the entry being replaced.\n * @param  {Package-object|null} pkg Package object for this entry, if exists.\n * @param  {string[]} sources Array of agent hashes involved in this mod.\n * @return {boolean} true if this entry may replace 'replaces'.\n *\n * @see https://developer.holochain.org/API#validateMod_entryType_entry_header_replaces_package_sources\n * @see https://developer.holochain.org/Validation_Functions\n */\nfunction validateMod (entryType, entry, header, replaces, pkg, sources) {\n  return validateCommit(entryType, entry, header, pkg, sources)\n    // Only allow the creator of the entity to modify it.\n    && getCreator(header.EntryLink) === getCreator(replaces);\n}\n\n/**\n * Validation callback: Can this entry be deleted?\n *\n * @param  {string} entryType Name of the entry as per DNA config for this zome.\n * @param  {string} hash The hash of the entry to be deleted.\n * @param  {Package-object|null} pkg Package object for this entry, if exists.\n * @param  {string[]} sources Array of agent hashes involved in this delete.\n * @return {boolean} true if this entry can be deleted.\n *\n * @see https://developer.holochain.org/API#validateDel_entryType_hash_package_sources\n * @see https://developer.holochain.org/Validation_Functions\n */\nfunction validateDel (entryType, hash, pkg, sources) {\n  return isValidEntryType(entryType)\n    // Only allow the creator of the entity to delete it.\n    && getCreator(hash) === sources[0];\n}\n\n/**\n * Package callback: The package request for validateCommit() and valdiatePut().\n *\n * Both 'commit' and 'put' trigger 'validatePutPkg' as 'validateCommit' and\n * 'validatePut' must both have the same data.\n *\n * @param  {string} entryType Name of the entry as per DNA config for this zome.\n * @return {PkgReq-object|null}\n *   null if the data required is the Entry and Header.\n *   Otherwise a \"Package Request\" object, which specifies what data to be sent\n *   to the validating node.\n *\n * @see https://developer.holochain.org/API#validatePutPkg_entryType\n * @see https://developer.holochain.org/Validation_Packaging\n */\nfunction validatePutPkg (entryType) {\n  return null;\n}\n\n/**\n * Package callback: The package request for validateMod().\n *\n * @param  {string} entryType Name of the entry as per DNA config for this zome.\n * @return {PkgReq-object|null}\n *   null if the data required is the Entry and Header.\n *   Otherwise a \"Package Request\" object, which specifies what data to be sent\n *   to the validating node.\n *\n * @see https://developer.holochain.org/API#validateModPkg_entryType\n * @see https://developer.holochain.org/Validation_Packaging\n */\nfunction validateModPkg (entryType) {\n  return null;\n}\n\n/**\n * Package callback: The package request for validateDel().\n *\n * @param  {string} entryType Name of the entry as per DNA config for this zome.\n * @return {PkgReq-object|null}\n *   null if the data required is the Entry and Header.\n *   Otherwise a \"Package Request\" object, which specifies what data to be sent\n *   to the validating node.\n *\n * @see https://developer.holochain.org/API#validateDelPkg_entryType\n * @see https://developer.holochain.org/Validation_Packaging\n */\nfunction validateDelPkg (entryType) {\n  return null;\n}"
    }
  ]},
"TestSets":[{
  "Name":"sample",
  "TestSet":{"Tests":[{"Convey":"Example: (which fails because we haven't actually implemented a sampleEntryCreate function) We can create a new sampleEntry","Zome":"sampleZome","FnName": "sampleEntryCreate","Input": {"content": "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 BytesSentChan chan BytesSent
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 DelEntryDef = &EntryDef{Name: DelEntryType, DataFormat: DataFormatJSON, Sharing: Public, Schema: DelEntrySchema}
View Source
var EnableAllLoggersEnv string = "HC_ENABLE_ALL_LOGS"
View Source
var ErrActionMissingHeader error = errors.New("Action is missing header")
View Source
var ErrActionReceiveInvalid error = errors.New("Action receive is invalid")
View Source
var ErrBlockedListed = errors.New("node blockedlisted")
View Source
var ErrBundleNotStarted = errors.New("bundle not started")
View Source
var ErrChainLockedForBundle = errors.New("chain locked for bundle")
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 ErrEntryDefInvalid = errors.New("Invalid Entry Defintion")
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 ErrModInvalidForLinks error = errors.New("mod: invalid for Links entry")
View Source
var ErrModMissingHeader error = errors.New("mod: missing header")
View Source
var ErrModReplacesHashNotDifferent error = errors.New("mod: replaces must be different from original hash")
View Source
var ErrNilEntryInvalid error = errors.New("nil entry invalid")
View Source
var ErrNoSuchIdx error = errors.New("no such change index")
View Source
var ErrNodeNotFound = errors.New("node not found")
View Source
var ErrNotAcceptedByAnyRemoteNode = errors.New("Change not accepted by any remote node")
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 ErrNotValidForDelType error = errors.New("Invalid action for Del type")
View Source
var ErrNotValidForHeadersType error = errors.New("Invalid action for Headers 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 HeadersEntryDef = &EntryDef{Name: HeadersEntryType, DataFormat: DataFormatJSON, Sharing: Public, Schema: HeadersEntrySchema}
View Source
var KValue int = 10
View Source
var KeyEntryDef = &EntryDef{Name: KeyEntryType, DataFormat: DataFormatSysKey}
View Source
var MigrateEntryDef = &EntryDef{Name: MigrateEntryType, DataFormat: DataFormatJSON, Sharing: Public, Schema: MigrateEntrySchema}
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(ValidationFailedErrMsg)
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 DecodeFile

func DecodeFile(data interface{}, pathParts ...string) (err error)

DecodeFile decodes a file based on the extension and the data type

func DecodePubKey

func DecodePubKey(b58pk string) (pubKey ic.PubKey, err error)

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 EscapeJSONValue

func EscapeJSONValue(json string) string

EscapeJSONValue removed characters from a JSON value to avoid parsing issues.

func FileExists

func FileExists(pathParts ...string) bool

func FileSize

func FileSize(pathParts ...string) int64

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 HoldingTask

func HoldingTask(h *Holochain)

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 IsValidationFailedErr

func IsValidationFailedErr(err error) bool

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 MakeReceiptData

func MakeReceiptData(msg *Message, code int) (reciept []byte, err error)

MakeReceiptData converts a message and a code into signable data

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 NormaliseJSON

func NormaliseJSON(json string) string

func Panix

func Panix(on string)

func PrepareTestChain

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

func PrettyPrintJSON

func PrettyPrintJSON(b []byte) (string, error)

PrettyPrintJSON for human reability.

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)

RetryTask checks to see if there are any received puts that need retrying and does one if so

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 SetAgentIdentity

func SetAgentIdentity(agent Agent, identity AgentIdentity)

func SetIdentity

func SetIdentity(h *Holochain, identity AgentIdentity)

func SetupTestChain

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

func SetupTestDir

func SetupTestDir() string

func ShouldLog

func ShouldLog(log *Logger, fn func(), messages ...string)

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 ValidationFailed

func ValidationFailed(msgs ...string) error

ValidationFailed creates a validation failed error message

func WriteFile

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

Types

type APIFnBridge

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

func (*APIFnBridge) Args

func (fn *APIFnBridge) Args() []Arg

func (*APIFnBridge) Call

func (fn *APIFnBridge) Call(h *Holochain) (response interface{}, err error)

func (*APIFnBridge) Name

func (fn *APIFnBridge) Name() string

type APIFnCall

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

func (*APIFnCall) Args

func (fn *APIFnCall) Args() []Arg

func (*APIFnCall) Call

func (fn *APIFnCall) Call(h *Holochain) (response interface{}, err error)

func (*APIFnCall) Name

func (fn *APIFnCall) Name() string

type APIFnCloseBundle

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

func (*APIFnCloseBundle) Args

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

func (*APIFnCloseBundle) Call

func (a *APIFnCloseBundle) Call(h *Holochain) (response interface{}, err error)

func (*APIFnCloseBundle) Name

func (a *APIFnCloseBundle) Name() string

type APIFnCommit

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

func (*APIFnCommit) Args

func (fn *APIFnCommit) Args() []Arg

func (*APIFnCommit) Call

func (fn *APIFnCommit) Call(h *Holochain) (response interface{}, err error)

func (*APIFnCommit) Name

func (fn *APIFnCommit) Name() string

func (*APIFnCommit) SetAction

func (fn *APIFnCommit) SetAction(a *ActionCommit)

type APIFnDebug

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

func (*APIFnDebug) Args

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

func (*APIFnDebug) Call

func (a *APIFnDebug) Call(h *Holochain) (response interface{}, err error)

func (*APIFnDebug) Name

func (a *APIFnDebug) Name() string

type APIFnDel

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

func (*APIFnDel) Args

func (fn *APIFnDel) Args() []Arg

func (*APIFnDel) Call

func (fn *APIFnDel) Call(h *Holochain) (response interface{}, err error)

func (*APIFnDel) Name

func (fn *APIFnDel) Name() string

type APIFnGet

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

func (*APIFnGet) Args

func (fn *APIFnGet) Args() []Arg

func (*APIFnGet) Call

func (fn *APIFnGet) Call(h *Holochain) (response interface{}, err error)

func (*APIFnGet) Name

func (fn *APIFnGet) Name() string

type APIFnGetBridges

type APIFnGetBridges struct {
}

func (*APIFnGetBridges) Args

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

func (*APIFnGetBridges) Call

func (a *APIFnGetBridges) Call(h *Holochain) (response interface{}, err error)

func (*APIFnGetBridges) Name

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

func (*APIFnGetLinks) Args

func (fn *APIFnGetLinks) Args() []Arg

func (*APIFnGetLinks) Call

func (fn *APIFnGetLinks) Call(h *Holochain) (response interface{}, err error)

func (*APIFnGetLinks) Name

func (fn *APIFnGetLinks) Name() string

type APIFnMakeHash

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

func (*APIFnMakeHash) Args

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

func (*APIFnMakeHash) Call

func (a *APIFnMakeHash) Call(h *Holochain) (response interface{}, err error)

func (*APIFnMakeHash) Name

func (a *APIFnMakeHash) Name() string

type APIFnMigrate

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

func (*APIFnMigrate) Args

func (fn *APIFnMigrate) Args() []Arg

func (*APIFnMigrate) Call

func (fn *APIFnMigrate) Call(h *Holochain) (response interface{}, err error)

func (*APIFnMigrate) Name

func (fn *APIFnMigrate) Name() string

type APIFnMod

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

func (*APIFnMod) Args

func (fn *APIFnMod) Args() []Arg

func (*APIFnMod) Call

func (fn *APIFnMod) Call(h *Holochain) (response interface{}, err error)

func (*APIFnMod) Name

func (fn *APIFnMod) Name() string

type APIFnModAgent

type APIFnModAgent struct {
	Identity   AgentIdentity
	Revocation string
}

func (*APIFnModAgent) Args

func (fn *APIFnModAgent) Args() []Arg

func (*APIFnModAgent) Call

func (fn *APIFnModAgent) Call(h *Holochain) (response interface{}, err error)

func (*APIFnModAgent) Name

func (fn *APIFnModAgent) Name() string

type APIFnProperty

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

func (*APIFnProperty) Args

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

func (*APIFnProperty) Call

func (a *APIFnProperty) Call(h *Holochain) (response interface{}, err error)

func (*APIFnProperty) Name

func (a *APIFnProperty) Name() string

type APIFnQuery

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

func (*APIFnQuery) Args

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

func (*APIFnQuery) Call

func (a *APIFnQuery) Call(h *Holochain) (response interface{}, err error)

func (*APIFnQuery) Name

func (a *APIFnQuery) Name() string

type APIFnSend

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

func (*APIFnSend) Args

func (fn *APIFnSend) Args() []Arg

func (*APIFnSend) Call

func (fn *APIFnSend) Call(h *Holochain) (response interface{}, err error)

func (*APIFnSend) Name

func (fn *APIFnSend) Name() string

type APIFnSign

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

func (*APIFnSign) Args

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

func (*APIFnSign) Call

func (a *APIFnSign) Call(h *Holochain) (response interface{}, err error)

func (*APIFnSign) Name

func (a *APIFnSign) Name() string

type APIFnStartBundle

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

func NewStartBundleAction

func NewStartBundleAction(timeout int, userParam string) *APIFnStartBundle

func (*APIFnStartBundle) Args

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

func (*APIFnStartBundle) Call

func (a *APIFnStartBundle) Call(h *Holochain) (response interface{}, err error)

func (*APIFnStartBundle) Name

func (a *APIFnStartBundle) Name() string

type APIFnVerifySignature

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

func (*APIFnVerifySignature) Args

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

func (*APIFnVerifySignature) Call

func (a *APIFnVerifySignature) Call(h *Holochain) (response interface{}, err error)

func (*APIFnVerifySignature) Name

func (a *APIFnVerifySignature) Name() string

type APIFunction

type APIFunction interface {
	Name() string
	Args() []Arg
	Call(h *Holochain) (response interface{}, err error)
}

APIFunction abstracts the argument structure and the calling of an api function

type Action

type Action interface {
	Name() string
	Receive(dht *DHT, msg *Message) (response interface{}, err error)
}

Action provides an abstraction for handling node interaction

func MakeActionFromMessage

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

MakeActionFromMessage generates an action from an action protocol messsage

type ActionCommit

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

func NewCommitAction

func NewCommitAction(entryType string, entry Entry) *ActionCommit

func (*ActionCommit) CheckValidationRequest

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

func (*ActionCommit) Entry

func (a *ActionCommit) Entry() Entry

func (*ActionCommit) EntryType

func (a *ActionCommit) EntryType() string

func (*ActionCommit) GetHeader

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

func (*ActionCommit) Name

func (a *ActionCommit) Name() string

func (*ActionCommit) Receive

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

func (*ActionCommit) SetHeader

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

func (*ActionCommit) Share

func (a *ActionCommit) Share(h *Holochain, def *EntryDef) (err error)

func (*ActionCommit) SysValidation

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

type ActionDel

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

func NewDelAction

func NewDelAction(entry DelEntry) *ActionDel

func (*ActionDel) CheckValidationRequest

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

func (*ActionDel) Entry

func (a *ActionDel) Entry() Entry

func (*ActionDel) EntryType

func (a *ActionDel) EntryType() string

func (*ActionDel) GetHeader

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

func (*ActionDel) Name

func (a *ActionDel) Name() string

func (*ActionDel) Receive

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

func (*ActionDel) SetHeader

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

func (*ActionDel) Share

func (a *ActionDel) Share(h *Holochain, def *EntryDef) (err error)

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
}

func (*ActionGet) Name

func (a *ActionGet) Name() string

func (*ActionGet) Receive

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

func (*ActionGet) SysValidation

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

func NewGetLinksAction

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

func (*ActionGetLinks) Name

func (a *ActionGetLinks) Name() string

func (*ActionGetLinks) Receive

func (a *ActionGetLinks) Receive(dht *DHT, msg *Message) (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) CheckValidationRequest

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

func (*ActionLink) Name

func (a *ActionLink) Name() string

func (*ActionLink) Receive

func (a *ActionLink) Receive(dht *DHT, msg *Message) (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) Name

func (a *ActionListAdd) Name() string

func (*ActionListAdd) Receive

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

type ActionMigrate

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

func (*ActionMigrate) CheckValidationRequest

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

func (*ActionMigrate) Entry

func (a *ActionMigrate) Entry() Entry

func (*ActionMigrate) EntryType

func (a *ActionMigrate) EntryType() string

func (*ActionMigrate) GetHeader

func (a *ActionMigrate) GetHeader() (header *Header)

func (*ActionMigrate) Name

func (a *ActionMigrate) Name() string

func (*ActionMigrate) Receive

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

func (*ActionMigrate) SetHeader

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

func (*ActionMigrate) Share

func (action *ActionMigrate) Share(h *Holochain, def *EntryDef) (err error)

func (*ActionMigrate) SysValidation

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

type ActionMod

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

func NewModAction

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

func (*ActionMod) CheckValidationRequest

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

func (*ActionMod) Entry

func (a *ActionMod) Entry() Entry

func (*ActionMod) EntryType

func (a *ActionMod) EntryType() string

func (*ActionMod) GetHeader

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

func (*ActionMod) Name

func (a *ActionMod) Name() string

func (*ActionMod) Receive

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

func (*ActionMod) SetHeader

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

func (*ActionMod) Share

func (a *ActionMod) Share(h *Holochain, def *EntryDef) (err error)

func (*ActionMod) SysValidation

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

type ActionPut

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

func NewPutAction

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

func (*ActionPut) CheckValidationRequest

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

func (*ActionPut) Name

func (a *ActionPut) Name() string

func (*ActionPut) Receive

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

func (*ActionPut) SysValidation

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

type ActionSend

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

func (*ActionSend) Name

func (a *ActionSend) Name() string

func (*ActionSend) Receive

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

type Agent

type Agent interface {
	Identity() AgentIdentity
	SetIdentity(id AgentIdentity)
	AgentType() AgentType
	GenKeys(seed io.Reader) error
	PrivKey() ic.PrivKey
	PubKey() ic.PubKey
	EncodePubKey() (string, error)
	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 string // marshaled revocation
	PublicKey  string // marshaled public key
}

AgentEntry structure for building AgentEntryType entries

func AgentEntryFromJSON

func AgentEntryFromJSON(j string) (entry AgentEntry, err error)

func (*AgentEntry) ToJSON

func (ae *AgentEntry) ToJSON() (encodedEntry string, err error)

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
}

Arg holds the definition of an API function argument

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 {
	CalleeApp  Hash
	CalleeName string
	Token      string
	Side       int
}

Bridge holds data returned by GetBridges

type BridgeApp

type BridgeApp struct {
	Name                    string //Name of other side
	DNA                     Hash   // DNA of other side
	Side                    int
	BridgeGenesisCallerData string
	BridgeGenesisCalleeData string
	Port                    string // only used if side == BridgeCallee
	BridgeZome              string // only used if side == BridgeCaller
}

BridgeApp describes a data necessary for bridging

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 Bundle

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

type BuntHT

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

func (*BuntHT) Close

func (ht *BuntHT) Close()

Close cleans up any resources used by the table

func (*BuntHT) Del

func (ht *BuntHT) Del(m *Message, key Hash) (err error)

Del moves the given hash to the StatusDeleted status N.B. this functions assumes that the validity of this action has been confirmed

func (ht *BuntHT) DelLink(m *Message, base string, link string, tag string) (err error)

DelLink removes a link and tag associated with a stored hash N.B. this function assumes that the action has been properly validated

func (*BuntHT) Exists

func (ht *BuntHT) Exists(key Hash, statusMask int) (err error)

Exists checks for the existence of the hash in the store

func (*BuntHT) Get

func (ht *BuntHT) Get(key Hash, statusMask int, getMask int) (data []byte, entryType string, sources []string, status int, err error)

Get retrieves a value from the DHT store

func (*BuntHT) GetIdx

func (ht *BuntHT) GetIdx() (idx int, err error)

GetIdx returns the current index of changes to the HashTable

func (*BuntHT) GetIdxMessage

func (ht *BuntHT) GetIdxMessage(idx int) (msg Message, err error)

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

func (ht *BuntHT) GetLinks(base Hash, tag string, statusMask int) (results []TaggedHash, err error)

GetLinks retrieves meta value associated with a base

func (*BuntHT) Iterate

func (ht *BuntHT) Iterate(fn HashTableIterateFn)

func (*BuntHT) JSON

func (ht *BuntHT) JSON() (result string, err error)

JSON converts the table into a JSON string representation.

func (*BuntHT) Mod

func (ht *BuntHT) Mod(m *Message, key Hash, newkey Hash) (err error)

Mod moves the given hash to the StatusModified status N.B. this functions assumes that the validity of this action has been confirmed

func (*BuntHT) Open

func (ht *BuntHT) Open(options interface{}) (err error)

func (*BuntHT) Put

func (ht *BuntHT) Put(m *Message, entryType string, key Hash, src peer.ID, value []byte, status int) (err error)

Put stores a value to the DHT store N.B. This call assumes that the value has already been validated

func (ht *BuntHT) PutLink(m *Message, base string, link string, tag string) (err error)

PutLink associates a link with a stored hash N.B. this function assumes that the data associated has been properly retrieved and validated from the cource chain

func (*BuntHT) Source

func (ht *BuntHT) Source(key Hash) (id peer.ID, err error)

Source returns the source node address of a given hash

func (*BuntHT) String

func (ht *BuntHT) String() (result string)

String converts the table into a human readable string

type BytesSent

type BytesSent struct {
	Bytes   int64
	MsgType MsgType
}

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[Hash]int   // map header hashes to index number
	Emap     map[Hash]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) BundleStarted

func (c *Chain) BundleStarted() *Bundle

BundleStarted returns the index of the chain item before the bundle or 0 if no bundle is active

func (*Chain) Close

func (c *Chain) Close()

Close the chain's file

func (*Chain) CloseBundle

func (c *Chain) CloseBundle(commit bool) (err error)

CloseBundle closes a started bundle and if commit copies entries from the bundle onto the chain

func (*Chain) Dot

func (c *Chain) Dot(start int) (dump string, err error)

Dot converts a chain to a GraphViz 'dot' format dump of the headers and entries

func (*Chain) Dump

func (c *Chain) Dump(start int) string

Dump converts a chain to a textual dump of the headers and entries from a starting index

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) JSON

func (c *Chain) JSON(start int) (string, error)

JSON converts a chain to a json string dump of the headers and entries

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) StartBundle

func (c *Chain) StartBundle(userParam interface{}) (err error)

StartBundle marks a bundle start point and returns an error if already started

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 Channel

type Channel chan interface{}

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
	// Performs all validation logic, including sysValidation (must be called explicitly)
	SysValidation(h *Holochain, def *EntryDef, pkg *Package, sources []peer.ID) (err error)
	Receive(dht *DHT, msg *Message) (response interface{}, err error)
	CheckValidationRequest(def *EntryDef) (err error)
	EntryType() string
	// returns a GobEntry containing the action's entry in a serialized format
	Entry() Entry
	SetHeader(header *Header)
	GetHeader() (header *Header)
	// Low level implementation of putting to DHT (assumes validation has been done)
	Share(h *Holochain, def *EntryDef) (err error)
}

CommittingAction provides an abstraction for grouping actions which carry Entry data

type Config

type Config struct {
	DHTPort          int
	EnableMDNS       bool
	PeerModeAuthor   bool
	PeerModeDHTNode  bool
	EnableNATUPnP    bool
	EnableWorldModel 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) Del

func (dht *DHT) Del(m *Message, key Hash) (err error)

Del moves the given hash to the StatusDeleted status N.B. this functions assumes that the validity of this action has been confirmed

func (dht *DHT) DelLink(m *Message, base string, link string, tag string) (err error)

DelLink removes a link and tag associated with a stored hash N.B. this function assumes that the action has been properly validated

func (*DHT) DeleteGossiper

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

DeleteGossiper removes a gossiper from the database

func (*DHT) Exists

func (dht *DHT) Exists(key Hash, statusMask int) (err error)

Exists checks for the existence of the hash in the store

func (*DHT) FindGossiper

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

FindGossiper picks a random DHT node to gossip with

func (*DHT) Get

func (dht *DHT) Get(key Hash, statusMask int, getMask int) (data []byte, entryType string, sources []string, status int, err error)

Get retrieves a value from the DHT store

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) GetGossipers

func (dht *DHT) GetGossipers() (gossipers []GossiperData, err error)

func (*DHT) GetIdx

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

GetIdx returns the current index of changes to the HashTable

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 *DHT) GetLinks(base Hash, tag string, statusMask int) (results []TaggedHash, err error)

GetLinks retrieves meta value associated with a base

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) HandleChangeRequests

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

HandleChangeRequests waits on a channel for dht change requests

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) Iterate

func (dht *DHT) Iterate(fn HashTableIterateFn)

func (*DHT) JSON

func (dht *DHT) JSON() (result string, err error)

JSON converts a DHT into a JSON string representation.

func (*DHT) MakeHoldResp

func (dht *DHT) MakeHoldResp(msg *Message, status int) (holdResp *HoldResp, err error)

MakeHoldResp creates fill the HoldResp struct with a the holding status and signature

func (*DHT) MakeReceiptSignature

func (dht *DHT) MakeReceiptSignature(msg *Message, code int) (sig Signature, err error)

MakeReceipt creates a signature of a message together with the receipt code

func (*DHT) Mod

func (dht *DHT) Mod(m *Message, key Hash, newkey Hash) (err error)

Mod moves the given hash to the StatusModified status N.B. this functions assumes that the validity of this action has been confirmed

func (*DHT) Open

func (dht *DHT) Open(options interface{}) (err error)

Open sets up the DHTs data structures and store

func (*DHT) Put

func (dht *DHT) Put(m *Message, entryType string, key Hash, src peer.ID, value []byte, status int) (err error)

Put stores a value to the DHT store N.B. This call assumes that the value has already been validated

func (dht *DHT) PutLink(m *Message, base string, link string, tag string) (err error)

PutLink associates a link with a stored hash N.B. this function assumes that the data associated has been properly retrieved and validated from the cource chain

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) Source

func (dht *DHT) Source(key Hash) (id peer.ID, err error)

Source returns the source node address of a given hash

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 HashType

	//RedundancyFactor(integer) Establishes minimum online redundancy targets for data, and size of peer sets for sync gossip. A redundancy factor 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.
	RedundancyFactor int
}

Holds the dht configuration options

type DNA

type DNA struct {
	Version              int
	UUID                 uuid.UUID
	Name                 string
	Properties           map[string]string
	PropertiesSchema     string
	PropertiesSchemaFile 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
	RequiresVersion      int
	DHTConfig            DHTConfig
	Progenitor           Progenitor
	Zomes                []ZomeFile
}

type DelEntry

type DelEntry struct {
	Hash    Hash
	Message string
}

DelEntry struct holds the record of an entry's deletion

func DelEntryFromJSON

func DelEntryFromJSON(j string) (entry DelEntry, err error)

func (*DelEntry) ToJSON

func (e *DelEntry) ToJSON() (encodedEntry string, err error)

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
	Bundle     bool // bool if get should happen from bundle 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 GossiperData

type GossiperData struct {
	ID     peer.ID
	PutIdx int
}

type HashTable

type HashTable interface {

	// Open initializes the table
	Open(options interface{}) (err error)

	// Close cleans up any resources used by the table
	Close()

	// Put stores a value to the DHT store
	Put(msg *Message, entryType string, key Hash, src peer.ID, value []byte, status int) (err error)

	// Del moves the given hash to the StatusDeleted status
	Del(msg *Message, key Hash) (err error)

	// Mod moves the given hash to the StatusModified status
	Mod(msg *Message, key Hash, newkey Hash) (err error)

	// Exists checks for the existence of the hash in the table
	Exists(key Hash, statusMask int) (err error)

	// Source returns the source node address of a given hash
	Source(key Hash) (id peer.ID, err error)

	// Get retrieves a value from the DHT store
	Get(key Hash, statusMask int, getMask int) (data []byte, entryType string, sources []string, status int, err error)

	// PutLink associates a link with a stored hash
	PutLink(m *Message, base string, link string, tag string) (err error)

	// DelLink removes a link and tag associated with a stored hash
	DelLink(m *Message, base string, link string, tag string) (err error)

	// GetLinks retrieves meta value associated with a base
	GetLinks(base Hash, tag string, statusMask int) (results []TaggedHash, err error)

	// GetIdx returns the current index of changes to the HashTable
	GetIdx() (idx int, err error)

	// GetIdxMessage returns the messages that causes the change at a given index
	GetIdxMessage(idx int) (msg Message, err error)

	// String converts the table into a human readable string
	String() string

	// JSON converts a DHT into a JSON string representation.
	JSON() (result string, err error)

	// Iterate call fn on all the hashes in the table
	Iterate(fn HashTableIterateFn)
}

HashTable provides an abstraction for storing the necessary DHT data

type HashTableIterateFn

type HashTableIterateFn func(hash Hash) (stop bool)

type HashType

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

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) ToJSON

func (hd *Header) ToJSON() (result string, err error)

ToJSON serializes a header to JSON

func (*Header) Unmarshal

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

Unmarshal reads a header from bytes

type HoldReq

type HoldReq struct {
	EntryHash   Hash // hash of the entry responsible for the change
	RelatedHash Hash // hash of the related entry (link=base,del=deleted, mod=modified by)
}

HoldReq holds the data of a change

type HoldResp

type HoldResp struct {
	Code      int
	Signature Signature
}

HoldResp holds the signature and code of how a hold request was treated

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(bridgeZome string, calleeDNA Hash, calleeName string, 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 in the bridgeZome

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) BuildBridgeToCallee

func (h *Holochain) BuildBridgeToCallee(app *BridgeApp) (err error)

BuildBridgeToCallee connects h to a running app specified by BridgeApp that will be the Callee, i.e. the the BridgeCallee

func (*Holochain) BuildBridgeToCaller

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

BuildBridgeToCaller connects h to a running app specified by BridgeApp that will be the Caller, i.e. the the BridgeCaller

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 @see https://github.com/holochain/holochain-proto/issues/730

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) Overlap

func (h *Holochain) Overlap(hash Hash) (overlap []peer.ID, err error)

Overlap returns a list of all the nodes that overlap for a given hash

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) RedundancyFactor

func (h *Holochain) RedundancyFactor() int

RedundancyFactor returns the redundancy that was set in the DNA

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(data []byte) (signature Signature, err error)

Sign uses the agent's private key to sign the contents of data

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 Signature, data string, pubKey ic.PubKey) (matches bool, err error)

VerifySignature uses the signature, data and the given public key to Verify the data was signed by holder of that key

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) World

func (h *Holochain) World() *World

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) BundleCanceled

func (jsr *JSRibosome) BundleCanceled(reason string) (response string, err error)

BundleCancel calls the app bundleCanceled function

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) EncodePubKey

func (a *LibP2PAgent) EncodePubKey() (b58pk string, err error)

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 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 LinksEntry

type LinksEntry struct {
	Links []Link
}

LinksEntry holds one or more links

func LinksEntryFromJSON

func LinksEntryFromJSON(j string) (entry LinksEntry, err error)

func (*LinksEntry) ToJSON

func (ae *LinksEntry) ToJSON() (encodedEntry string, err error)

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
	World      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 MigrateEntry

type MigrateEntry struct {
	Type    string
	DNAHash Hash
	Key     Hash
	Data    string
}

MigrateEntry struct is the record of a chain opening or closing

func MigrateEntryFromJSON

func MigrateEntryFromJSON(j string) (entry MigrateEntry, err error)

func (*MigrateEntry) ToJSON

func (e *MigrateEntry) ToJSON() (encodedEntry string, err error)

type ModAgentOptions

type ModAgentOptions struct {
	Identity   string
	Revocation string
}

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
)

@TODO don't have order dependant constants https://github.com/holochain/holochain-proto/issues/713

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 NodeRecord

type NodeRecord struct {
	PeerInfo  pstore.PeerInfo
	PubKey    ic.PubKey
	IsHolding map[Hash]bool
}

NodeRecord stores the necessary information about other nodes in the world model

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 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
	Bundle    bool
}

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() (string, error)
	Unmarshal(string) 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)
	BundleCanceled(reason string) (response string, 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 string, err error)

func (*SelfRevocation) Unmarshal

func (r *SelfRevocation) Unmarshal(data string) (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
}

func SignatureFromB58String

func SignatureFromB58String(encoded string) (sig Signature)

SignatureFromB58String encodes a signature as a b58string

func (Signature) B58String

func (sig Signature) B58String() (result string)

B58String encodes a signature as a b58string

func (Signature) Equal

func (sig1 Signature) Equal(sig2 Signature) bool

Equal tests signature equality

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       interface{}   // the expected error to match against
	ErrMsg    string        // the expected error message 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
	Benchmark bool          // activate benchmarking for this test
}

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
	Benchmark bool // activate benchmarking for all tests
}

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
	SysValidation(h *Holochain, def *EntryDef, pkg *Package, sources []peer.ID) (err error)
	Receive(dht *DHT, msg *Message) (response interface{}, err error)
	CheckValidationRequest(def *EntryDef) (err error)
}

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 World

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

World holds the data of a nodes' world model

func NewWorld

func NewWorld(me peer.ID, ht HashTable, logger *Logger) *World

NewWorld creates and empty world model

func (*World) AddNode

func (world *World) AddNode(pi pstore.PeerInfo, pubKey ic.PubKey) (err error)

AddNode adds a node to the world model

func (*World) AllNodes

func (world *World) AllNodes() (nodes []peer.ID, err error)

AllNodes returns a list of all the nodes in the world model.

func (*World) GetNodeRecord

func (world *World) GetNodeRecord(ID peer.ID) (record *NodeRecord)

GetNodeRecord returns the peer's node record NOTE: do not modify the contents of the returned record! not thread safe

func (*World) IsHolding

func (world *World) IsHolding(ID peer.ID, hash Hash) (holding bool, err error)

IsHolding returns whether a node is holding a particular hash

func (*World) Responsible

func (world *World) Responsible() (entries []Hash, err error)

Responsible returns a list of all the entries I'm responsible for holding

func (*World) SetNodeHolding

func (world *World) SetNodeHolding(ID peer.ID, hash Hash) (err error)

SetNodeHolding marks a node as holding a particular hash

func (*World) UpdateResponsible

func (world *World) UpdateResponsible(hash Hash, redundancy int) (responsible bool, err error)

UpdateResponsible calculates the list of nodes believed to be responsible for a given hash note that if redundancy is 0 the assumption is that all nodes are responsible

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 callerApp
	//	BridgeCallee Hash     // dna Hash of provider App that this zome will call
	Config map[string]interface{}
}

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
	RibosomeType string
	BridgeFuncs  []string // functions in zome that can be bridged to by fromApp
	Config       map[string]interface{}
	Entries      []EntryDefFile
	Functions    []FunctionDef
}

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) BundleCanceled

func (z *ZygoRibosome) BundleCanceled(reason string) (response string, err error)

BundleCancel calls the app bundleCanceled function

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