documents

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2020 License: MIT Imports: 47 Imported by: 0

Documentation

Overview

Package documents implements Centrifuge document models.

Models

The idea of having a model is to make the business functions of the document clearer and more readable. This also enables proper types and validations on the fields that require them. When an API call is received, the following list of transformations/steps needs to be executed on the request object.

1. Model conversion: this would ensure that proper types are created for each of the fields of the input document plus handling basic level validations that does not require business level understanding of the document. eg: telephone numbers, IDs

2. The converted model is updated using the existing document. After this there would be two versions of the document in the system old and the new

3. The two versions of the document are passed through a purpose specific validator chain that implements the following interface. (see chapter on validation)

Model Storage

A model objects must support storage in DB as a JSON serialized object. The rationale behind this is that JSON format enables easier inter-operability between systems that would depend on database access such as BI (Although we do NOT recommend directly accessing the db eventually when we have proper APIs for accessing all data).

// example of an implementation
type InvoiceModel struct {
// all invoice fields with proper types here
}

func (i *InvoiceModel) PackCoreDocument() *coredocumentpb.CoreDocument {
panic("implement me")
}

func (i *InvoiceModel) UnpackCoreDocument(cd *coredocumentpb.CoreDocument) error {
panic("implement me")
}

func (i *InvoiceModel) JSON() ([]byte, error) {
panic("implement me")
}

func (i *InvoiceModel) Type() reflect.Type {
return reflect.TypeOf(i)
}

Model Package Hierarchy Specification

In the new package structure the package `documents` includes all model relevant implementations and interfaces. The actual implementation can be found at the package `invoice` or `purchaseorder`. The package `documents` should not include any of the actual implementations to avoid cycle dependencies.

Validation

Validations should be done depending on the situation. The below table is an example that shows a few examples of validations that should only depending on context of the validation.

|                           | Verify  SigningRoot | Verify DocumentRoot | Check Invoice State Transition | Node must be in collaborators |
|---------------------------|---------------------|---------------------|--------------------------------|-------------------------------|
| Client Submission         |                     |                     | yes                            | yes                           |
| Signature Request         | yes                 |                     |                                |                               |
| Receive Anchored Document | yes                 | yes                 |                                | yes                           |
| Store in DB               | yes                 | only if set         |                                | yes                           |

Validations are implemented in individual checks. These individual checks can be nested in different grouped set of validations. Validators all implement the Validator interface to allow simple nesting of checks.

There are three types of validators:

1. **Atomic Validators:** they validate an individual field or several fields and contain actual checking of certain values, checking of an anchor etc. Atomic validators are never split up. Anything an atomic validator validates would always be validated as one block.

2. **Internal Group Validations:** contain a collection of atomic validators but these are not grouped by purpose but elements that are reused in other validators (group or purpose validators)

3. **Purpose Validators:** these validators are public and used by the application logic to validate a document. They should never be used inside of other validators. Code performing validation should always call a purpose validator but never an internal group directly.

type interface Validator {
// Validate validates the updates to the model in newState. errors returned must always be centerrors
Validate(oldState Model, newState Model) []error
}

// ValidatorGroup implements Validator for executing a set of validators.
type ValidatorGroup struct {
[]Validator validators
}
func (group *ValidatorGroup) Validate(oldState Model, newState Model) (validationErrors []error) {

for v, i := range group.validators {
validationErrors = append(validationErrors, v.Validate(oldState, newState))
}
}

// An implementation of ValidatorGroup as an example.
// Note that this is not a public validator but merely a private variable that can be reused in validators.
var invoiceHeaderValidators = ValidatorGroup{
validators: []Validator{
Field1Validator,
Field2Validator,
Field3Validator
}
}

// An implementation of a Validator that is used by other services
// Note that this is public
var ValidateOnSignatureRequest = ValidatorGroup{
validators: []Validator{
invoiceHeaderValidator, ...
}
}

Controllers, Services and Their Relationship with Models

1. Controllers

Controllers are generally the first contact point between an external request and the application logic. The implementations would just pass control over to a request specific `Service` layer call.

2. Services

Services in the CentNode must deal with only specific Model object plus its related objects. Eg: InvoiceService would only deal with InvoiceModel. Since in many cases a model object may need to be created based on some external input such as a coredocument, the following are some good base interfaces for a service to implement,

// Implementation of deriving model objects
type InvoiceService struct { }

func (srv *InvoiceService) DeriveFromCoreDocument(cd *coredocument.CoreDocument) (*InvoiceModel, error) {
panic("Implement me");
}

func (srv *InvoiceService)  DeriveWithCreateInvoiceInput(*CreateInvoiceInput) (*InvoiceModel, error) {
panic("Implement me");
}

Service Registry

To locate a service that could handle operations for a given CoreDocument object a service registry needs to be developed. This would use the `coreDocument.EmbeddedData.TypeUrl` to map the document to the relevant service.

// in documents/registry.go

func LocateService(cd *coredocument.CoreDocument) (ModelDeriver, error) {
....
}

Every service should be able to `register` itself at the `ServiceRegistry` if it implements the `ModelDeriver` interface.

func (s *ServiceRegistry) Register(serviceID string, service ModelDeriver) error

The registry should be thread safe.

A Sample Flow for Handling Document Signature Requests

The following is an example modification of `Handler.RequestDocumentSignature` to show the usage of `Registry`, `Service` and `Model` interactions.

func (srv *Handler) RequestDocumentSignature(ctx context.Context, sigReq *p2ppb.SignatureRequest) (*p2ppb.SignatureResponse, error) {
service, err := registry.LocateService(sigReq.Document)
if err != nil {
return nil, err
}

model, err := service.DeriveWithCD(sigReq.Document)
if err != nil {
return nil, err
}

if p2pService, ok := service.(P2PSignatureRequestHandler); ok {
sig, errors := p2pService.Sign(model)
if len(errs) != 0 {
return nil, centerrors.NewWithErrors(errs)
}
return &p2ppb.SignatureResponse{
CentNodeVersion: version.GetVersion().String(),
Signature:       sig,
}, nil
}

return nil, someerrorThatcausedServiceMismatch

}

Index

Constants

View Source
const (
	// DocumentIDParam maps to model ID in the kwargs
	DocumentIDParam = "documentID"

	// AccountIDParam maps to account ID in the kwargs
	AccountIDParam = "accountID"
)
View Source
const (
	// AttrInt256 is the standard integer custom attribute type
	AttrInt256 AttributeType = "integer"

	// AttrDecimal is the standard big decimal custom attribute type
	AttrDecimal AttributeType = "decimal"

	// AttrString is the standard string custom attribute type
	AttrString AttributeType = "string"

	// AttrBytes is the standard bytes custom attribute type
	AttrBytes AttributeType = "bytes"

	// AttrTimestamp is the standard time stamp custom attribute type
	AttrTimestamp AttributeType = "timestamp"

	// AttrSigned is the custom signature attribute type
	AttrSigned AttributeType = "signed"

	// AttrMonetary is the monetary attribute type
	AttrMonetary AttributeType = "monetary"

	// MonetaryToken is the monetary type for tokens
	MonetaryToken MonetaryType = "token"
)
View Source
const (
	// BootstrappedRegistry is the key to ServiceRegistry in Bootstrap context
	BootstrappedRegistry = "BootstrappedRegistry"

	// BootstrappedDocumentRepository is the key to the database repository of documents
	BootstrappedDocumentRepository = "BootstrappedDocumentRepository"

	// BootstrappedDocumentService is the key to bootstrapped document service
	BootstrappedDocumentService = "BootstrappedDocumentService"

	// BootstrappedAnchorProcessor is the key to bootstrapped anchor processor
	BootstrappedAnchorProcessor = "BootstrappedAnchorProcessor"
)
View Source
const (
	// ErrComputeFieldsInvalidWASM is a sentinel error for invalid WASM blob
	ErrComputeFieldsInvalidWASM = errors.Error("Invalid WASM blob")

	// ErrComputeFieldsAllocateNotFound is a sentinel error when WASM doesn't expose 'allocate' function
	ErrComputeFieldsAllocateNotFound = errors.Error("'allocate' function not exported")

	// ErrComputeFieldsComputeNotFound is a sentinel error when WASM doesn't expose 'compute' function
	ErrComputeFieldsComputeNotFound = errors.Error("'compute' function not exported")
)
View Source
const (

	// CDRootField represents the coredocument root property of a tree
	CDRootField = "cd_root"

	// DataRootField represents the data root property of a tree
	DataRootField = "data_root"

	// DocumentTypeField represents the doc type property of a tree
	DocumentTypeField = "document_type"

	// BasicDataRootField represents the basic document data tree root
	BasicDataRootField = "bd_root"

	// ZKDataRootField represents the zk document data tree root
	ZKDataRootField = "zkd_root"

	// SignaturesRootField represents the signatures property of a tree
	SignaturesRootField = "signatures_root"

	// SigningRootField represents the signature root property of a tree
	SigningRootField = "signing_root"

	// DRTreePrefix is the human readable prefix for document root tree props
	DRTreePrefix = "dr_tree"

	// CDTreePrefix is the human readable prefix for core doc tree props
	CDTreePrefix = "cd_tree"

	// BasicDataRootPrefix represents the basic document data tree
	BasicDataRootPrefix = "bdr_tree"

	// ZKDataRootPrefix represents the zk document data tree
	ZKDataRootPrefix = "zkdr_tree"

	// SigningTreePrefix is the human readable prefix for signing tree props
	SigningTreePrefix = "signing_tree"

	// SignaturesTreePrefix is the human readable prefix for signature props
	SignaturesTreePrefix = "signatures_tree"

	// Pending status represents document is in pending state
	Pending Status = "pending"

	// Committing status represents document is being committed.
	Committing Status = "committing"

	// Committed status represents document is committed/anchored.
	Committed Status = "committed"
)
View Source
const (

	// ErrDocumentConfigAccountID must be used for errors related to accountID operations
	ErrDocumentConfigAccountID = errors.Error("error with accountID operations")

	// ErrDocumentBootstrap must be used for errors related to documents package bootstrapping
	ErrDocumentBootstrap = errors.Error("error when bootstrapping documents package")

	// ErrDocumentIdentifier must be used for errors caused by document identifier problems
	ErrDocumentIdentifier = errors.Error("document identifier error")

	// ErrDocumentInvalidType must be used when a provided document type is not valid to be processed by the service
	ErrDocumentInvalidType = errors.Error("document is of invalid type")

	// ErrDocumentNil must be used when the provided document through a function is nil
	ErrDocumentNil = errors.Error("no(nil) document provided")

	// ErrPayloadNil must be used when a required payload is nil
	ErrPayloadNil = errors.Error("no(nil) payload provided")

	// ErrDocumentSchemeUnknown is a sentinel error when the scheme provided is missing in the registry.
	ErrDocumentSchemeUnknown = errors.Error("unknown document scheme provided")

	// ErrDocumentInvalid must only be used when the reason for invalidity is impossible to determine or the invalidity is caused by validation errors
	ErrDocumentInvalid = errors.Error("document is invalid")

	// ErrDocumentNotFound must be used to indicate that the document for provided id is not found in the system
	ErrDocumentNotFound = errors.Error("document not found in the system database")

	// ErrDocumentVersionNotFound must be used to indicate that the specified version of the document for provided id is not found in the system
	ErrDocumentVersionNotFound = errors.Error("specified version of the document not found in the system database")

	// ErrDocumentPersistence must be used when creating or updating a document in the system database failed
	ErrDocumentPersistence = errors.Error("error encountered when storing document in the system database")

	// ErrDocumentUnPackingCoreDocument must be used when unpacking of core document for the given document failed
	ErrDocumentUnPackingCoreDocument = errors.Error("core document unpacking failed")

	// ErrDocumentPackingCoreDocument must be used when packing of core document for the given document failed
	ErrDocumentPackingCoreDocument = errors.Error("core document packing failed")

	// ErrDocumentAnchoring must be used when document anchoring fails
	ErrDocumentAnchoring = errors.Error("document anchoring failed")

	// ErrDocumentProof must be used when document proof creation fails
	ErrDocumentProof = errors.Error("document proof error")

	// ErrNotPatcher must be used if an expected patcher model does not support patching
	ErrNotPatcher = errors.Error("document doesn't support patching")

	// ErrCDCreate must be used for coredoc creation/generation errors
	ErrCDCreate = errors.Error("error creating core document")

	// ErrCDClone must be used for coredoc clone errors
	ErrCDClone = errors.Error("error cloning core document")

	// ErrCDNewVersion must be used for coredoc creation/generation errors
	ErrCDNewVersion = errors.Error("error creating new version of core document")

	// ErrCDTree must be used when there are errors during precise-proof tree and root generation
	ErrCDTree = errors.Error("error when generating trees/roots")

	// ErrCDAttribute must be used when there are errors caused by custom model attributes
	ErrCDAttribute = errors.Error("model attribute error")

	// ErrCDStatus is a sentinel error used when status is being chnaged from Committed to anything else.
	ErrCDStatus = errors.Error("cannot change the status of a committed document")

	// ErrDocumentNotInAllowedState is a sentinel error used when a document is not in allowed state for certain op
	ErrDocumentNotInAllowedState = errors.Error("document is not in allowed state")

	// ErrDataTree must be used for data tree errors
	ErrDataTree = errors.Error("getDataTree error")

	// ErrNftNotFound must be used when the NFT is not found in the document
	ErrNftNotFound = errors.Error("nft not found in the Document")

	// ErrNftByteLength must be used when there is a byte length mismatch
	ErrNftByteLength = errors.Error("byte length mismatch")

	// ErrAccessTokenInvalid must be used when the access token is invalid
	ErrAccessTokenInvalid = errors.Error("access token is invalid")

	// ErrAccessTokenNotFound must be used when the access token was not found
	ErrAccessTokenNotFound = errors.Error("access token not found")

	// ErrRequesterNotGrantee must be used when the document requester is not the grantee of the access token
	ErrRequesterNotGrantee = errors.Error("requester is not the same as the access token grantee")

	// ErrGranterNotCollab must be used when the granter of the access token is not a collaborator on the document
	ErrGranterNotCollab = errors.Error("access token granter is not a collaborator on this document")

	// ErrReqDocNotMatch must be used when the requested document does not match the access granted by the access token
	ErrReqDocNotMatch = errors.Error("the document requested does not match the document to which the access token grants access")

	// ErrNFTRoleMissing errors when role to generate proof doesn't exist
	ErrNFTRoleMissing = errors.Error("NFT Role doesn't exist")

	// ErrInvalidIDLength must be used when the identifier bytelength is not 32
	ErrInvalidIDLength = errors.Error("invalid identifier length")

	// ErrDocumentNotLatest must be used if document is not the latest version
	ErrDocumentNotLatest = errors.Error("document is not the latest version")

	// ErrModelNil must be used if the model is nil
	ErrModelNil = errors.Error("model is empty")

	// ErrInvalidDecimal must be used when given decimal is invalid
	ErrInvalidDecimal = errors.Error("invalid decimal")

	// ErrInvalidInt256 must be used when given 256 bit signed integer is invalid
	ErrInvalidInt256 = errors.Error("invalid 256 bit signed integer")

	// ErrIdentityNotOwner must be used when an identity which does not own the entity relationship attempts to update the document
	ErrIdentityNotOwner = errors.Error("identity attempting to update the document does not own this entity relationship")

	// ErrNotImplemented must be used when an method has not been implemented
	ErrNotImplemented = errors.Error("Method not implemented")

	// ErrDocumentConfigNotInitialised is a sentinel error when document config is missing
	ErrDocumentConfigNotInitialised = errors.Error("document config not initialised")

	// ErrDifferentAnchoredAddress is a sentinel error when anchor address is different from the configured one.
	ErrDifferentAnchoredAddress = errors.Error("anchor address is not the node configured address")

	// ErrDocumentIDReused is a sentinel error when identifier is re-used
	ErrDocumentIDReused = errors.Error("document identifier is already used")

	// ErrNotValidAttrType is a sentinel error when an unknown attribute type is given
	ErrNotValidAttrType = errors.Error("not a valid attribute type")

	// ErrEmptyAttrLabel is a sentinel error when the attribute label is empty
	ErrEmptyAttrLabel = errors.Error("empty attribute label")

	// ErrWrongAttrFormat is a sentinel error when the attribute format is wrong
	ErrWrongAttrFormat = errors.Error("wrong attribute format")

	// ErrDocumentValidation must be used when document validation fails
	ErrDocumentValidation = errors.Error("document validation failure")

	// ErrRoleNotExist must be used when role doesn't exist in the document.
	ErrRoleNotExist = errors.Error("role doesn't exist")

	// ErrRoleExist must be used when role exist in the document.
	ErrRoleExist = errors.Error("role already exists")

	// ErrEmptyRoleKey must be used when role key is empty
	ErrEmptyRoleKey = errors.Error("empty role key")

	// ErrEmptyCollaborators must be used when collaborator list is empty
	ErrEmptyCollaborators = errors.Error("empty collaborators")

	// ErrInvalidRoleKey must be used when role key is not 32 bytes long
	ErrInvalidRoleKey = errors.Error("role key is invalid")

	// ErrTransitionRuleMissing is a sentinel error used when transition rule is missing from the document.
	ErrTransitionRuleMissing = errors.Error("transition rule missing")

	// ErrTemplateAttributeMissing is an error when the template attribute is missing
	ErrTemplateAttributeMissing = errors.Error("template attribute missing")
)
View Source
const (
	// DocPrefix holds the generic prefix of a document in DB
	DocPrefix string = "document_"

	// LatestPrefix is used to index latest version of the document.
	LatestPrefix string = "latest_document_"
)
View Source
const MaxAuthoredToCommitDuration = 120 * time.Minute

MaxAuthoredToCommitDuration is the maximum allowed time period for a document to be anchored after a authoring it based on document timestamp. I.E. This is basically the maximum time period allowed for document consensus to complete as well.

Variables

This section is empty.

Functions

func CompactProperties

func CompactProperties(key string) []byte

CompactProperties returns the compact property for a given prefix

func ConsensusSignaturePayload added in v1.0.0

func ConsensusSignaturePayload(dataRoot []byte, validated bool) []byte

ConsensusSignaturePayload forms the payload needed to be signed during the document consensus flow

func ConstructNFT

func ConstructNFT(registry common.Address, tokenID []byte) ([]byte, error)

ConstructNFT appends registry and tokenID to byte slice

func CreateAnchorJob added in v1.0.0

func CreateAnchorJob(parentCtx context.Context, jobsMan jobs.Manager, tq queue.TaskQueuer, self identity.DID, jobID jobs.JobID, documentID []byte) (jobs.JobID, chan error, error)

CreateAnchorJob creates a job for anchoring a document using jobs manager

func DecimalsToBytes

func DecimalsToBytes(decs ...*Decimal) ([][]byte, error)

DecimalsToBytes converts decimals to bytes

func DecimalsToStrings

func DecimalsToStrings(decs ...*Decimal) []string

DecimalsToStrings converts decimals to string. nil decimal leads to empty string.

func IsCurrencyValid

func IsCurrencyValid(cur string) bool

IsCurrencyValid checks if the currency is of length 3

func NewError

func NewError(key, msg string) error

NewError creates a new error from a key and a msg. Deprecated: in favour of Error type in `github.com/centrifuge/go-centrifuge/errors`

func NewLeafProperty

func NewLeafProperty(literal string, compact []byte) proofs.Property

NewLeafProperty returns a proof property with the literal and the compact

func ToProtocolAttachments added in v1.0.0

func ToProtocolAttachments(atts []*BinaryAttachment) []*commonpb.BinaryAttachment

ToProtocolAttachments converts Binary Attchments to protocol attachments.

func ToProtocolPaymentDetails added in v1.0.0

func ToProtocolPaymentDetails(details []*PaymentDetails) ([]*commonpb.PaymentDetails, error)

ToProtocolPaymentDetails converts payment details to protocol payment details

func ValidateProof added in v1.0.0

func ValidateProof(proof *proofspb.Proof, rootHash []byte, hashFunc hash.Hash, leafHashFunc hash.Hash) (valid bool, err error)

ValidateProof by comparing it to the provided rootHash

func ValidateTransitions

func ValidateTransitions(rules []coredocumentpb.TransitionRule, changedFields []ChangedField) error

ValidateTransitions validates the changedFields based on the rules provided. returns an error if any ChangedField violates the rules.

Types

type AccessTokenParams added in v1.0.0

type AccessTokenParams struct {
	Grantee, DocumentIdentifier string
}

AccessTokenParams holds details of Grantee and DocumentIdentifier.

type AnchorProcessor

type AnchorProcessor interface {
	Send(ctx context.Context, cd coredocumentpb.CoreDocument, recipient identity.DID) (err error)
	PrepareForSignatureRequests(ctx context.Context, model Model) error
	RequestSignatures(ctx context.Context, model Model) error
	PrepareForAnchoring(model Model) error
	PreAnchorDocument(ctx context.Context, model Model) error
	AnchorDocument(ctx context.Context, model Model) error
	SendDocument(ctx context.Context, model Model) error
}

AnchorProcessor identifies an implementation, which can do a bunch of things with a CoreDocument. E.g. send, anchor, etc.

func DefaultProcessor

func DefaultProcessor(idService identity.Service, p2pClient Client, anchorSrv anchors.Service, config Config) AnchorProcessor

DefaultProcessor returns the default implementation of CoreDocument AnchorProcessor

type AttrKey added in v1.0.0

type AttrKey [32]byte

AttrKey represents a sha256 hash of a attribute label given by a user.

func AttrKeyFromBytes added in v1.0.0

func AttrKeyFromBytes(b []byte) (AttrKey, error)

AttrKeyFromBytes converts bytes to AttrKey

func AttrKeyFromLabel added in v1.0.0

func AttrKeyFromLabel(label string) (attrKey AttrKey, err error)

AttrKeyFromLabel creates a new AttrKey from label.

func (AttrKey) MarshalText added in v1.0.0

func (a AttrKey) MarshalText() (text []byte, err error)

MarshalText converts the AttrKey to its text form

func (AttrKey) String added in v1.0.0

func (a AttrKey) String() string

String converts the AttrKey to a hex string

func (*AttrKey) UnmarshalText added in v1.0.0

func (a *AttrKey) UnmarshalText(text []byte) error

UnmarshalText converts text to AttrKey

type AttrVal added in v1.0.0

type AttrVal struct {
	Type      AttributeType
	Int256    *Int256
	Decimal   *Decimal
	Str       string
	Bytes     []byte
	Timestamp *timestamp.Timestamp
	Signed    Signed
	Monetary  Monetary
}

AttrVal represents a strongly typed value of an attribute

func AttrValFromString added in v1.0.0

func AttrValFromString(attrType AttributeType, value string) (attrVal AttrVal, err error)

AttrValFromString converts the string value to necessary type based on the attribute type.

func (AttrVal) String added in v1.0.0

func (attrVal AttrVal) String() (str string, err error)

String returns the string representation of the AttrVal.

func (AttrVal) ToBytes added in v1.0.0

func (attrVal AttrVal) ToBytes() ([]byte, error)

ToBytes encodes attribute value into bytes.

type Attribute added in v1.0.0

type Attribute struct {
	KeyLabel string
	Key      AttrKey
	Value    AttrVal
}

Attribute represents a custom attribute of a document

func NewMonetaryAttribute added in v1.0.0

func NewMonetaryAttribute(keyLabel string, value *Decimal, chainID []byte, id string) (attr Attribute, err error)

NewMonetaryAttribute creates new instance of Monetary Attribute

func NewSignedAttribute added in v1.0.0

func NewSignedAttribute(keyLabel string, identity identity.DID, account config.Account, docID, versionID, value []byte, valType AttributeType) (attr Attribute, err error)

NewSignedAttribute returns a new signed attribute takes keyLabel, signer identity, signer account, model and value doc version is next version of the document since that is the document version in which the attribute is added. signature payload: sign(identity + docID + docNextVersion + value) Note: versionID should always be the next version that is going to be anchored.

func NewStringAttribute added in v1.0.0

func NewStringAttribute(keyLabel string, attrType AttributeType, value string) (attr Attribute, err error)

NewStringAttribute creates a new custom attribute.

type AttributeType added in v1.0.0

type AttributeType string

AttributeType represents the custom attribute type.

func (AttributeType) String added in v1.0.0

func (a AttributeType) String() string

String returns the readable name of the attribute type.

type BinaryAttachment

type BinaryAttachment struct {
	Name     string             `json:"name"`
	FileType string             `json:"file_type"` // mime type of attached file
	Size     int                `json:"size"`      // in bytes
	Data     byteutils.HexBytes `json:"data" swaggertype:"primitive,string"`
	Checksum byteutils.HexBytes `json:"checksum" swaggertype:"primitive,string"` // the md5 checksum of the original file for easier verification
}

BinaryAttachment represent a single file attached to invoice.

func FromProtocolAttachments added in v1.0.0

func FromProtocolAttachments(patts []*commonpb.BinaryAttachment) []*BinaryAttachment

FromProtocolAttachments converts Protocol attachments to Binary Attachments

type Bootstrapper

type Bootstrapper struct{}

Bootstrapper implements bootstrap.Bootstrapper.

func (Bootstrapper) Bootstrap

func (Bootstrapper) Bootstrap(ctx map[string]interface{}) error

Bootstrap sets the required storage and registers

type ChangedField

type ChangedField struct {
	Property, Old, New []byte
	Name               string
}

ChangedField holds the compact property, old and new value of the field that is changed if the old is nil, then it is a set operation if new is nil, then it is an unset operation if both old and new are set, then it is an edit operation

func GetChangedFields

func GetChangedFields(oldTree, newTree *proofs.DocumentTree) (changedFields []ChangedField)

GetChangedFields takes two document trees and returns the compact property, old and new value of the fields that are changed in new tree. Properties may have been added to the new tree or removed from the new tree. In Either case, since the new tree is different from old, that is considered a change.

type Client

type Client interface {

	// GetSignaturesForDocument gets the signatures for document
	GetSignaturesForDocument(ctx context.Context, model Model) ([]*coredocumentpb.Signature, []error, error)

	// after all signatures are collected the sender sends the document including the signatures
	SendAnchoredDocument(ctx context.Context, receiverID identity.DID, in *p2ppb.AnchorDocumentRequest) (*p2ppb.AnchorDocumentResponse, error)

	// GetDocumentRequest requests a document from a collaborator
	GetDocumentRequest(ctx context.Context, requesterID identity.DID, in *p2ppb.GetDocumentRequest) (*p2ppb.GetDocumentResponse, error)
}

Client defines methods that can be implemented by any type handling p2p communications.

type ClonePayload added in v1.2.0

type ClonePayload struct {
	Scheme     string
	TemplateID []byte
}

ClonePayload holds the scheme, CollaboratorsAccess, Attributes, Data and document identifier.

type CollaboratorsAccess

type CollaboratorsAccess struct {
	ReadCollaborators      []identity.DID
	ReadWriteCollaborators []identity.DID
}

CollaboratorsAccess allows us to differentiate between the types of access we want to give new collaborators

type Config

type Config interface {
	GetNetworkID() uint32
	GetIdentityID() ([]byte, error)
	GetP2PConnectionTimeout() time.Duration
	GetContractAddress(contractName config.ContractName) common.Address
}

Config defines required methods required for the documents package.

type CoreDocument

type CoreDocument struct {
	// Modified indicates that the CoreDocument has been modified and salts needs to be generated for new fields in coredoc precise-proof tree.
	Modified bool

	// Attributes are the custom attributes added to the document
	Attributes map[AttrKey]Attribute

	// Status represents document status.
	Status Status

	Document coredocumentpb.CoreDocument
}

CoreDocument is a wrapper for CoreDocument Protobuf.

func NewClonedDocument added in v1.2.0

func NewClonedDocument(d coredocumentpb.CoreDocument) (*CoreDocument, error)

NewClonedDocument generates new blank core document with a document type specified by the prefix: generic. It then copies the Transition rules, Read rules, Roles, and Attributes of a supplied Template document.

func NewCoreDocument added in v1.0.0

func NewCoreDocument(documentPrefix []byte, collaborators CollaboratorsAccess, attributes map[AttrKey]Attribute) (*CoreDocument, error)

NewCoreDocument generates new core document with a document type specified by the prefix: po or invoice. It then adds collaborators, adds read rules and fills salts.

func NewCoreDocumentFromProtobuf

func NewCoreDocumentFromProtobuf(cd coredocumentpb.CoreDocument) (coreDoc *CoreDocument, err error)

NewCoreDocumentFromProtobuf returns CoreDocument from the CoreDocument Protobuf.

func NewCoreDocumentWithAccessToken

func NewCoreDocumentWithAccessToken(ctx context.Context, documentPrefix []byte, params AccessTokenParams) (*CoreDocument, error)

NewCoreDocumentWithAccessToken generates a new core document with a document type specified by the prefix. It also adds the targetID as a read collaborator, and adds an access token on this document for the document specified in the documentID parameter

func (*CoreDocument) ATGranteeCanRead

func (cd *CoreDocument) ATGranteeCanRead(ctx context.Context, docService Service, idService identity.Service, tokenID, docID []byte, requesterID identity.DID) (err error)

ATGranteeCanRead checks that the grantee of the access token can read the document requested

func (*CoreDocument) AccountCanRead

func (cd *CoreDocument) AccountCanRead(account identity.DID) bool

AccountCanRead validate if the core document can be read by the account . Returns an error if not.

func (*CoreDocument) AddAccessToken

func (cd *CoreDocument) AddAccessToken(ctx context.Context, payload AccessTokenParams) (*CoreDocument, error)

AddAccessToken adds the AccessToken to the document

func (*CoreDocument) AddAttributes added in v1.0.0

func (cd *CoreDocument) AddAttributes(ca CollaboratorsAccess, prepareNewVersion bool, documentPrefix []byte, attrs ...Attribute) (*CoreDocument, error)

AddAttributes adds a custom attribute to the model with the given value. If an attribute with the given name already exists, it's updated. Note: The prepareNewVersion flags defines if the returned model should be a new version of the document.

func (*CoreDocument) AddComputeFieldsRule added in v1.2.0

func (cd *CoreDocument) AddComputeFieldsRule(wasm []byte, fields []string, targetField string) (*coredocumentpb.TransitionRule, error)

AddComputeFieldsRule adds a new compute fields rule. wasm is the WASM blob fields are the attribute labels that are passed to wasm targetField is the attribute label under which WASM result is stored

func (*CoreDocument) AddNFT

func (cd *CoreDocument) AddNFT(grantReadAccess bool, registry common.Address, tokenID []byte) (*CoreDocument, error)

AddNFT returns a new CoreDocument model with nft added to the Core document. If grantReadAccess is true, the nft is added to the read rules.

func (*CoreDocument) AddRole added in v1.0.0

func (cd *CoreDocument) AddRole(key string, collabs []identity.DID) (*coredocumentpb.Role, error)

AddRole adds a new role to the document. key can either be plain text or 32 byte hex string, key cannot be empty If key is not 32 byte hex string, then the key is used as pre image for 32 byte key

func (*CoreDocument) AddTransitionRuleForAttribute added in v1.0.0

func (cd *CoreDocument) AddTransitionRuleForAttribute(roleID []byte, key AttrKey) (*coredocumentpb.TransitionRule, error)

AddTransitionRuleForAttribute adds a new rule with key as fields for the role FieldMatchType_FIELD_MATCH_TYPE_PREFIX will be used for the Field match for attributes TransitionAction_TRANSITION_ACTION_EDIT is the default action we assign to the rule. Role must be present to create a rule.

func (*CoreDocument) AddUpdateLog

func (cd *CoreDocument) AddUpdateLog(account identity.DID) (err error)

AddUpdateLog adds a log to the model to persist an update related meta data such as author

func (*CoreDocument) AnchorRepoAddress added in v1.0.0

func (cd *CoreDocument) AnchorRepoAddress() common.Address

AnchorRepoAddress returns the used anchor repo address to which the document is/will be anchored to.

func (*CoreDocument) AppendSignatures

func (cd *CoreDocument) AppendSignatures(signs ...*coredocumentpb.Signature)

AppendSignatures appends signatures to core document.

func (*CoreDocument) AttributeExists added in v1.0.0

func (cd *CoreDocument) AttributeExists(key AttrKey) bool

AttributeExists checks if an attribute associated with the key exists.

func (*CoreDocument) Author

func (cd *CoreDocument) Author() (identity.DID, error)

Author is the author of the document version represented by the model

func (*CoreDocument) CalculateDocumentRoot

func (cd *CoreDocument) CalculateDocumentRoot(docType string, dataLeaves []proofs.LeafNode) ([]byte, error)

CalculateDocumentRoot calculates the document root of the CoreDocument.

func (*CoreDocument) CalculateSignaturesRoot

func (cd *CoreDocument) CalculateSignaturesRoot() ([]byte, error)

CalculateSignaturesRoot returns the signatures root of the document.

func (*CoreDocument) CalculateSigningRoot

func (cd *CoreDocument) CalculateSigningRoot(docType string, dataLeaves []proofs.LeafNode) ([]byte, error)

CalculateSigningRoot calculates the signing root of the core document.

func (*CoreDocument) CalculateTransitionRulesFingerprint added in v1.2.0

func (cd *CoreDocument) CalculateTransitionRulesFingerprint() ([]byte, error)

CalculateTransitionRulesFingerprint generates a fingerprint for a Core Document

func (*CoreDocument) CollaboratorCanUpdate

func (cd *CoreDocument) CollaboratorCanUpdate(ncd *CoreDocument, collaborator identity.DID, docType string) error

CollaboratorCanUpdate validates the changes made by the collaborator in the new document. returns error if the transitions are not allowed for the collaborator.

func (*CoreDocument) CreateNFTProofs

func (cd *CoreDocument) CreateNFTProofs(
	docType string,
	dataLeaves []proofs.LeafNode,
	account identity.DID,
	registry common.Address,
	tokenID []byte,
	nftUniqueProof, readAccessProof bool) (prf *DocumentProof, err error)

CreateNFTProofs generate proofs returns proofs for NFT minting.

func (*CoreDocument) CreateProofs

func (cd *CoreDocument) CreateProofs(docType string, dataLeaves []proofs.LeafNode, fields []string) (*DocumentProof, error)

CreateProofs takes document data leaves and list of fields and generates proofs.

func (*CoreDocument) CreateProofsFromZKTree added in v1.0.0

func (cd *CoreDocument) CreateProofsFromZKTree(docType string, dataLeaves []proofs.LeafNode, fields []string) (*DocumentProof, error)

CreateProofsFromZKTree takes document data leaves and list of fields and generates proofs from ZK-ready Tree.

func (*CoreDocument) CurrentVersion

func (cd *CoreDocument) CurrentVersion() []byte

CurrentVersion returns the current version of the document

func (*CoreDocument) CurrentVersionPreimage

func (cd *CoreDocument) CurrentVersionPreimage() []byte

CurrentVersionPreimage returns the current version preimage of the document

func (*CoreDocument) DefaultOrderedTreeWithPrefix added in v1.0.0

func (cd *CoreDocument) DefaultOrderedTreeWithPrefix(prefix string, compactPrefix []byte) (*proofs.DocumentTree, error)

DefaultOrderedTreeWithPrefix returns a DocumentTree with default opts, sorted hashing disabled and passing a prefix to the tree leaves

func (*CoreDocument) DefaultTreeWithPrefix

func (cd *CoreDocument) DefaultTreeWithPrefix(prefix string, compactPrefix []byte) (*proofs.DocumentTree, error)

DefaultTreeWithPrefix returns a DocumentTree with default opts, sorted hashing enabled and passing a prefix to the tree leaves

func (*CoreDocument) DefaultZTreeWithPrefix added in v1.0.0

func (cd *CoreDocument) DefaultZTreeWithPrefix(prefix string, compactPrefix []byte) (*proofs.DocumentTree, error)

DefaultZTreeWithPrefix returns a DocumentTree for the ZK branch with default opts passing a prefix to the tree leaves

func (*CoreDocument) DeleteAccessToken

func (cd *CoreDocument) DeleteAccessToken(granteeID identity.DID) (*CoreDocument, error)

DeleteAccessToken deletes an access token on the Document

func (*CoreDocument) DeleteAttribute

func (cd *CoreDocument) DeleteAttribute(key AttrKey, prepareNewVersion bool, documentPrefix []byte) (*CoreDocument, error)

DeleteAttribute deletes a custom attribute from the model. If the attribute is missing, delete returns an error

func (*CoreDocument) DeleteTransitionRule added in v1.0.0

func (cd *CoreDocument) DeleteTransitionRule(ruleID []byte) error

DeleteTransitionRule deletes the rule associated with ruleID. once the rule is deleted, we will also delete roles from the default rules if the role is not associated with another rule.

func (*CoreDocument) DocumentRootTree

func (cd *CoreDocument) DocumentRootTree(docType string, dataLeaves []proofs.LeafNode) (tree *proofs.DocumentTree, err error)

DocumentRootTree returns the merkle tree for the document root.

func (*CoreDocument) DocumentSaltsFunc

func (cd *CoreDocument) DocumentSaltsFunc() func(compact []byte) ([]byte, error)

DocumentSaltsFunc returns a function that fetches and sets salts on the CoreDoc. The boolean `cd.Modified` can be used to define if the salts function should error if a new field is encountered or not.

func (*CoreDocument) ExecuteComputeFields added in v1.2.0

func (cd *CoreDocument) ExecuteComputeFields(timeout time.Duration) error

ExecuteComputeFields executes all the compute fields and updates the document with target attributes each WASM is executed at a max of timeout duration.

func (*CoreDocument) GetAccessTokens

func (cd *CoreDocument) GetAccessTokens() ([]*coredocumentpb.AccessToken, error)

GetAccessTokens returns the access tokens of a core document

func (*CoreDocument) GetAttribute

func (cd *CoreDocument) GetAttribute(key AttrKey) (attr Attribute, err error)

GetAttribute gets the attribute with the given name from the model together with its type, it returns a non-nil error if the attribute doesn't exist or can't be retrieved.

func (*CoreDocument) GetAttributes added in v1.0.0

func (cd *CoreDocument) GetAttributes() (attrs []Attribute)

GetAttributes returns all the attributes present in the coredocument.

func (*CoreDocument) GetCollaborators

func (cd *CoreDocument) GetCollaborators(filterIDs ...identity.DID) (CollaboratorsAccess, error)

GetCollaborators returns the collaborators excluding the filteredIDs

func (CoreDocument) GetComputeFieldsRules added in v1.2.0

func (cd CoreDocument) GetComputeFieldsRules() []*coredocumentpb.TransitionRule

GetComputeFieldsRules returns all the compute fields rules from the document.

func (*CoreDocument) GetRole added in v1.0.0

func (cd *CoreDocument) GetRole(key []byte) (*coredocumentpb.Role, error)

GetRole returns the role associated with key. key has to be 32 bytes long.

func (*CoreDocument) GetSignaturesDataTree added in v1.0.0

func (cd *CoreDocument) GetSignaturesDataTree() (tree *proofs.DocumentTree, err error)

GetSignaturesDataTree returns the merkle tree for the Signature Data root.

func (*CoreDocument) GetSignerCollaborators

func (cd *CoreDocument) GetSignerCollaborators(filterIDs ...identity.DID) ([]identity.DID, error)

GetSignerCollaborators returns the collaborators excluding the filteredIDs returns collaborators with Action_ACTION_READ_SIGN and TransitionAction_TRANSITION_ACTION_EDIT permissions.

func (*CoreDocument) GetStatus added in v1.0.0

func (cd *CoreDocument) GetStatus() Status

GetStatus returns document status

func (*CoreDocument) GetTransitionRule added in v1.0.0

func (cd *CoreDocument) GetTransitionRule(ruleID []byte) (*coredocumentpb.TransitionRule, error)

GetTransitionRule returns the transition rule associated with ruleID in the document.

func (*CoreDocument) ID

func (cd *CoreDocument) ID() []byte

ID returns the document identifier

func (*CoreDocument) IsDIDCollaborator

func (cd *CoreDocument) IsDIDCollaborator(did identity.DID) (bool, error)

IsDIDCollaborator returns true if the did is a collaborator of the document

func (*CoreDocument) IsNFTMinted

func (cd *CoreDocument) IsNFTMinted(tokenRegistry TokenRegistry, registry common.Address) bool

IsNFTMinted checks if the there is an NFT that is minted against this document in the given registry.

func (*CoreDocument) MarshalJSON added in v1.0.0

func (cd *CoreDocument) MarshalJSON(m Model) ([]byte, error)

MarshalJSON marshals the model and returns the json data.

func (*CoreDocument) NFTOwnerCanRead

func (cd *CoreDocument) NFTOwnerCanRead(tokenRegistry TokenRegistry, registry common.Address, tokenID []byte, account identity.DID) error

NFTOwnerCanRead checks if the nft owner/account can read the Document

func (*CoreDocument) NFTs

func (cd *CoreDocument) NFTs() []*coredocumentpb.NFT

NFTs returns the list of NFTs created for this model

func (*CoreDocument) NextVersion

func (cd *CoreDocument) NextVersion() []byte

NextVersion returns the next version of the document.

func (*CoreDocument) PackCoreDocument

func (cd *CoreDocument) PackCoreDocument(data *any.Any) coredocumentpb.CoreDocument

PackCoreDocument prepares the document into a core document.

func (*CoreDocument) Patch added in v1.0.0

func (cd *CoreDocument) Patch(documentPrefix []byte, collaborators CollaboratorsAccess, attrs map[AttrKey]Attribute) (*CoreDocument, error)

Patch overrides only core document data without provisioning new versions since for document updates

func (*CoreDocument) PrepareNewVersion

func (cd *CoreDocument) PrepareNewVersion(documentPrefix []byte, collaborators CollaboratorsAccess, attrs map[AttrKey]Attribute) (*CoreDocument, error)

PrepareNewVersion prepares the next version of the CoreDocument if initSalts is true, salts will be generated for new version.

func (*CoreDocument) PreviousVersion

func (cd *CoreDocument) PreviousVersion() []byte

PreviousVersion returns the previous version of the document.

func (*CoreDocument) RemoveCollaborators added in v1.0.0

func (cd *CoreDocument) RemoveCollaborators(dids []identity.DID) error

RemoveCollaborators removes DIDs from the Document. Errors out if the document is not in Pending state or collaborators are missing from the document.

func (*CoreDocument) SetStatus added in v1.0.0

func (cd *CoreDocument) SetStatus(st Status) error

SetStatus set the status of the document. if the document is already committed, returns an error if set status is called.

func (*CoreDocument) SetUsedAnchorRepoAddress added in v1.0.0

func (cd *CoreDocument) SetUsedAnchorRepoAddress(addr common.Address)

SetUsedAnchorRepoAddress sets used anchor repo address.

func (*CoreDocument) Signatures

func (cd *CoreDocument) Signatures() (signatures []coredocumentpb.Signature)

Signatures returns the copy of the signatures on the document.

func (*CoreDocument) SigningDataTrees added in v1.0.0

func (cd *CoreDocument) SigningDataTrees(docType string, dataLeaves []proofs.LeafNode) (trees []*proofs.DocumentTree, rootHash []byte, err error)

SigningDataTrees returns the merkle trees (basicData and zkData) + signingRoot Hash for the document data tree provided

func (*CoreDocument) Timestamp

func (cd *CoreDocument) Timestamp() (time.Time, error)

Timestamp is the time of update in UTC of the document version represented by the model

func (*CoreDocument) TransitionRulesFor

func (cd *CoreDocument) TransitionRulesFor(did identity.DID) (rules []coredocumentpb.TransitionRule)

TransitionRulesFor returns a copy all the transition rules for the DID.

func (*CoreDocument) UnmarshalJSON added in v1.0.0

func (cd *CoreDocument) UnmarshalJSON(data []byte, m Model) error

UnmarshalJSON unmarshals the data into model and set the attributes back to the document. Note: Coredocument should not be nil and should be initialised to the Model before passing to this function.

func (*CoreDocument) UpdateRole added in v1.0.0

func (cd *CoreDocument) UpdateRole(rk []byte, collabs []identity.DID) (*coredocumentpb.Role, error)

UpdateRole updates existing role with provided collaborators

type CreatePayload added in v1.0.0

type CreatePayload struct {
	Scheme        string
	Collaborators CollaboratorsAccess
	Attributes    map[AttrKey]Attribute
	Data          []byte
}

CreatePayload holds the scheme, CollaboratorsAccess, Attributes, and Data of the document.

type Decimal

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

Decimal holds a fixed point decimal

func BytesToDecimals

func BytesToDecimals(bytes ...[]byte) ([]*Decimal, error)

BytesToDecimals converts decimals in bytes to Decimal type

func DecimalFromBytes added in v1.0.0

func DecimalFromBytes(b []byte) (*Decimal, error)

DecimalFromBytes returns a new decimal from bytes

func NewDecimal added in v1.0.0

func NewDecimal(s string) (*Decimal, error)

NewDecimal returns a new decimal from given string

func StringsToDecimals

func StringsToDecimals(strs ...string) ([]*Decimal, error)

StringsToDecimals converts string decimals to Decimal type

func (*Decimal) Bytes

func (d *Decimal) Bytes() (decimal []byte, err error)

Bytes return the decimal in bytes. sign byte + upto 23 integer bytes + 8 decimal bytes

func (*Decimal) MarshalJSON

func (d *Decimal) MarshalJSON() ([]byte, error)

MarshalJSON marshals decimal to json bytes.

func (*Decimal) SetBytes

func (d *Decimal) SetBytes(dec []byte) error

SetBytes parse the bytes to Decimal.

func (*Decimal) SetString

func (d *Decimal) SetString(s string) error

SetString takes a decimal in string format and converts it into Decimal

func (*Decimal) String

func (d *Decimal) String() string

String returns the decimal in string representation.

func (*Decimal) UnmarshalJSON

func (d *Decimal) UnmarshalJSON(data []byte) error

UnmarshalJSON loads json bytes to decimal

type Deriver added in v1.0.0

type Deriver interface {
	// DeriveFromCreatePayload loads the payload into self.
	DeriveFromCreatePayload(ctx context.Context, payload CreatePayload) error

	// DeriveFromUpdatePayload create the next version of the document.
	// Patches the old data with Payload data
	DeriveFromUpdatePayload(ctx context.Context, payload UpdatePayload) (Model, error)

	// DeriveFromClonePayload clones the transition rules and roles from another document
	// and loads the payload into self
	DeriveFromClonePayload(ctx context.Context, m Model) error
}

Deriver defines the functions that can derive Document from the Payloads.

type DocumentProof

type DocumentProof struct {
	DocumentID     []byte
	VersionID      []byte
	State          string
	FieldProofs    []*proofspb.Proof
	LeftDataRooot  []byte
	RightDataRoot  []byte
	SigningRoot    []byte
	SignaturesRoot []byte
}

DocumentProof is a value to represent a document and its field proofs

type DocumentRequestProcessor

type DocumentRequestProcessor interface {
	RequestDocumentWithAccessToken(ctx context.Context, granterDID identity.DID, tokenIdentifier, documentIdentifier, delegatingDocumentIdentifier []byte) (*p2ppb.GetDocumentResponse, error)
}

DocumentRequestProcessor offers methods to interact with the p2p layer to request documents.

type Error

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

Error wraps an error with specific key Deprecated: in favour of Error type in `github.com/centrifuge/go-centrifuge/errors`

func (Error) Error

func (e Error) Error() string

Error returns the underlying error message

type Int256 added in v1.0.0

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

Int256 represents a signed 256 bit integer

func Int256FromBytes added in v1.0.0

func Int256FromBytes(b []byte) (*Int256, error)

Int256FromBytes converts the a big endian 2's complement byte slice to an Int256

func NewInt256 added in v1.0.0

func NewInt256(n string) (*Int256, error)

NewInt256 creates a new Int256 given a string

func (*Int256) Add added in v1.0.0

func (i *Int256) Add(x *Int256, y *Int256) (*Int256, error)

Add sets i to the sum x+y and returns i

func (Int256) Bytes added in v1.0.0

func (i Int256) Bytes() [32]byte

Bytes returns the big endian 2's complement 32 byte representation of this int256.

func (*Int256) Cmp added in v1.0.0

func (i *Int256) Cmp(y *Int256) int

Cmp compares i and y and returns:

-1 if i <  y
 0 if i == y
+1 if i >  y

func (*Int256) Equals added in v1.0.0

func (i *Int256) Equals(o *Int256) bool

Equals checks if the given two Int256s are equal

func (*Int256) Inc added in v1.0.0

func (i *Int256) Inc() (*Int256, error)

Inc increments i by one

func (*Int256) MarshalJSON added in v1.0.0

func (i *Int256) MarshalJSON() ([]byte, error)

MarshalJSON marshals decimal to json bytes.

func (*Int256) String added in v1.0.0

func (i *Int256) String() string

String converts Int256 to string

func (*Int256) UnmarshalJSON added in v1.0.0

func (i *Int256) UnmarshalJSON(data []byte) error

UnmarshalJSON loads json bytes to decimal

type Model

type Model interface {
	storage.Model

	// ID returns the document identifier
	ID() []byte

	// CurrentVersion returns the current version identifier of the document
	CurrentVersion() []byte

	// CurrentVersionPreimage returns the current version pre-image of the document. This is intended to hide the next version of an updated version of the document.
	CurrentVersionPreimage() []byte

	// PreviousVersion returns the previous version identifier of the document
	PreviousVersion() []byte

	// NextVersion returns the next version identifier of the document.
	NextVersion() []byte

	// PackCoreDocument packs the implementing document into a core document
	// Should only be called when the document is about to be put on wire.
	PackCoreDocument() (coredocumentpb.CoreDocument, error)

	// UnpackCoreDocument takes a core document protobuf and loads the data into the model.
	UnpackCoreDocument(cd coredocumentpb.CoreDocument) error

	// DocumentType returns the type of the document
	DocumentType() string

	// Scheme returns the scheme of the document data.
	// TODO(ved): remove once the DocumentType is not used anymore.
	Scheme() string

	// CalculateSigningRoot calculates the signing root of the model.
	CalculateSigningRoot() ([]byte, error)

	// CalculateDocumentRoot returns the document root of the model.
	CalculateDocumentRoot() ([]byte, error)

	// CalculateSignaturesRoot returns signatures root of the model.
	CalculateSignaturesRoot() ([]byte, error)

	// AppendSignatures appends the signatures to the model.
	AppendSignatures(signatures ...*coredocumentpb.Signature)

	// Signatures returns a copy of the signatures on the document
	Signatures() []coredocumentpb.Signature

	// CreateProofs creates precise-proofs for given fields
	CreateProofs(fields []string) (prf *DocumentProof, err error)

	// CreateNFTProofs creates NFT proofs for minting.
	CreateNFTProofs(
		account identity.DID,
		registry common.Address,
		tokenID []byte,
		nftUniqueProof, readAccessProof bool) (proof *DocumentProof, err error)

	// IsNFTMinted checks if there is any NFT minted for the registry given
	IsNFTMinted(tr TokenRegistry, registry common.Address) bool

	// AddNFT adds an NFT to the document.
	// Note: The document should be anchored after successfully adding the NFT.
	AddNFT(grantReadAccess bool, registry common.Address, tokenID []byte) error

	// NFTs returns the list of NFTs created for this model
	NFTs() []*coredocumentpb.NFT

	// GetCollaborators returns the collaborators of this document.
	// filter ids should not be returned
	// Note: returns all the collaborators with Read and Read_Sign permission
	GetCollaborators(filterIDs ...identity.DID) (CollaboratorsAccess, error)

	// GetSignerCollaborators works like GetCollaborators except it returns only those with Read_Sign permission.
	GetSignerCollaborators(filterIDs ...identity.DID) ([]identity.DID, error)

	// AccountCanRead returns true if the account can read the document
	AccountCanRead(account identity.DID) bool

	// NFTOwnerCanRead returns error if the NFT cannot read the document.
	NFTOwnerCanRead(tokenRegistry TokenRegistry, registry common.Address, tokenID []byte, account identity.DID) error

	// ATGranteeCanRead returns error if the access token grantee cannot read the document.
	ATGranteeCanRead(ctx context.Context, docSrv Service, idSrv identity.Service, tokenID, docID []byte, grantee identity.DID) (err error)

	// AddUpdateLog adds a log to the model to persist an update related meta data such as author
	AddUpdateLog(account identity.DID) error

	// Author is the author of the document version represented by the model
	Author() (identity.DID, error)

	// Timestamp is the time of update in UTC of the document version represented by the model
	Timestamp() (time.Time, error)

	// CollaboratorCanUpdate returns an error if indicated identity does not have the capacity to update the document.
	CollaboratorCanUpdate(updated Model, collaborator identity.DID) error

	// IsDIDCollaborator returns true if the did is a collaborator of the document
	IsDIDCollaborator(did identity.DID) (bool, error)

	// AddAttributes adds a custom attribute to the model with the given value. If an attribute with the given name already exists, it's updated.
	AddAttributes(ca CollaboratorsAccess, prepareNewVersion bool, attrs ...Attribute) error

	// GetAttribute gets the attribute with the given name from the model, it returns a non-nil error if the attribute doesn't exist or can't be retrieved.
	GetAttribute(key AttrKey) (Attribute, error)

	// GetAttributes returns all the attributes in the current document
	GetAttributes() []Attribute

	// DeleteAttribute deletes a custom attribute from the model
	DeleteAttribute(key AttrKey, prepareNewVersion bool) error

	// AttributeExists checks if the attribute with the key exists
	AttributeExists(key AttrKey) bool

	// GetAccessTokens returns the access tokens of a core document
	GetAccessTokens() ([]*coredocumentpb.AccessToken, error)

	// SetUsedAnchorRepoAddress sets the anchor repository address to which document is anchored to.
	SetUsedAnchorRepoAddress(addr common.Address)

	// AnchorRepoAddress returns the used anchor repo address to which document is/will be anchored to.
	AnchorRepoAddress() common.Address

	// GetData returns the document data. Ex: invoice.Data
	GetData() interface{}

	// GetStatus returns the status of the document.
	GetStatus() Status

	// SetStatus set the status of the document.
	SetStatus(st Status) error

	// RemoveCollaborators removes collaborators from the current document.
	RemoveCollaborators(dids []identity.DID) error

	// GetRole returns the role associated with key.
	GetRole(key []byte) (*coredocumentpb.Role, error)

	// AddRole adds a nw role to the document.
	AddRole(key string, collabs []identity.DID) (*coredocumentpb.Role, error)

	// UpdateRole updates existing role with provided collaborators
	UpdateRole(rk []byte, collabs []identity.DID) (*coredocumentpb.Role, error)

	// AddTransitionRules creates a new transition rule to edit an attribute.
	// The access is only given to the roleKey which is expected to be present already.
	AddTransitionRuleForAttribute(roleID []byte, key AttrKey) (*coredocumentpb.TransitionRule, error)

	// GetTransitionRule returns the transition rule associated with ruleID in the document.
	GetTransitionRule(ruleID []byte) (*coredocumentpb.TransitionRule, error)

	// DeleteTransitionRule deletes the rule associated with ruleID.
	DeleteTransitionRule(ruleID []byte) error

	// CalculateTransitionRulesFingerprint creates a fingerprint from the transition rules and roles of a document.
	CalculateTransitionRulesFingerprint() ([]byte, error)

	// AddComputeFieldsRule adds a new compute field rule
	AddComputeFieldsRule(wasm []byte, fields []string, targetField string) (*coredocumentpb.TransitionRule, error)

	// ExecuteComputeFields executes all the compute fields and updates the document with target attributes.
	ExecuteComputeFields(timeout time.Duration) error

	// GetComputeFieldsRules returns all the compute fields rules from the document.
	GetComputeFieldsRules() []*coredocumentpb.TransitionRule
}

Model is an interface to abstract away model specificness like invoice or purchaseOrder The interface can cast into the type specified by the model if required It should only handle protocol-level document actions

func AnchorDocument

func AnchorDocument(ctx context.Context, model Model, proc AnchorProcessor, updater updaterFunc, preAnchor bool) (Model, error)

AnchorDocument add signature, requests signatures, anchors document, and sends the anchored document to collaborators

type Monetary added in v1.0.0

type Monetary struct {
	Value   *Decimal
	ChainID []byte
	Type    MonetaryType
	ID      []byte // Currency USD|0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2(DAI)|ETH
}

Monetary is a custom attribute type for monetary values

func (Monetary) String added in v1.0.0

func (m Monetary) String() string

String returns the readable representation of the monetary value

type MonetaryType added in v1.0.0

type MonetaryType string

MonetaryType represents the monetary type of the attribute

func (MonetaryType) String added in v1.0.0

func (a MonetaryType) String() string

String returns the readable name of the monetary type.

type Patcher added in v1.0.0

type Patcher interface {
	// Patch merges payload data into model
	Patch(payload UpdatePayload) error
}

Patcher interface defines a Patch method for inner Models

type PaymentDetails

type PaymentDetails struct {
	ID                    string        `json:"id"` // identifying this payment. could be a sequential number, could be a transaction hash of the crypto payment
	DateExecuted          *time.Time    `json:"date_executed" swaggertype:"primitive,string"`
	Payee                 *identity.DID `json:"payee" swaggertype:"primitive,string"` // centrifuge id of payee
	Payer                 *identity.DID `json:"payer" swaggertype:"primitive,string"` // centrifuge id of payer
	Amount                *Decimal      `json:"amount" swaggertype:"primitive,string"`
	Currency              string        `json:"currency"`
	Reference             string        `json:"reference"` // payment reference (e.g. reference field on bank transfer)
	BankName              string        `json:"bank_name"`
	BankAddress           string        `json:"bank_address"`
	BankCountry           string        `json:"bank_country"`
	BankAccountNumber     string        `json:"bank_account_number"`
	BankAccountCurrency   string        `json:"bank_account_currency"`
	BankAccountHolderName string        `json:"bank_account_holder_name"`
	BankKey               string        `json:"bank_key"`

	CryptoChainURI      string `json:"crypto_chain_uri"`      // the ID of the chain to use in URI format. e.g. "ethereum://42/<tokenaddress>"
	CryptoTransactionID string `json:"crypto_transaction_id"` // the transaction in which the payment happened
	CryptoFrom          string `json:"crypto_from"`           // from address
	CryptoTo            string `json:"crypto_to"`             // to address
}

PaymentDetails holds the payment related details for invoice.

func FromProtocolPaymentDetails added in v1.0.0

func FromProtocolPaymentDetails(pdetails []*commonpb.PaymentDetails) ([]*PaymentDetails, error)

FromProtocolPaymentDetails converts protocol payment details to PaymentDetails

type PostBootstrapper

type PostBootstrapper struct{}

PostBootstrapper to run the post after all bootstrappers.

func (PostBootstrapper) Bootstrap

func (PostBootstrapper) Bootstrap(ctx map[string]interface{}) error

Bootstrap register task to the queue.

type Proof added in v1.0.0

type Proof struct {
	Property     byteutils.HexBytes   `json:"property" swaggertype:"primitive,string"`
	Value        byteutils.HexBytes   `json:"value" swaggertype:"primitive,string"`
	Salt         byteutils.HexBytes   `json:"salt" swaggertype:"primitive,string"`
	Hash         byteutils.HexBytes   `json:"hash" swaggertype:"primitive,string"`
	SortedHashes []byteutils.HexBytes `json:"sorted_hashes" swaggertype:"array,string"`
}

Proof represents a single proof

func ConvertProofs added in v1.0.0

func ConvertProofs(fieldProofs []*proofspb.Proof) []Proof

ConvertProofs converts proto proofs to JSON struct

type Repository

type Repository interface {
	// Exists checks if the id, owned by accountID, exists in DB
	Exists(accountID, id []byte) bool

	// Get returns the Model associated with ID, owned by accountID
	Get(accountID, id []byte) (Model, error)

	// Create creates the model if not present in the DB.
	// should error out if the document exists.
	Create(accountID, id []byte, model Model) error

	// Update strictly updates the model.
	// Will error out when the model doesn't exist in the DB.
	Update(accountID, id []byte, model Model) error

	// Register registers the model so that the DB can return the document without knowing the type
	Register(model Model)

	// GetLatest returns the latest version of the document.
	GetLatest(accountID, docID []byte) (Model, error)
}

Repository defines the required methods for a document repository. Can be implemented by any type that stores the documents. Ex: levelDB, sql etc...

func NewDBRepository

func NewDBRepository(db storage.Repository) Repository

NewDBRepository creates an instance of the documents Repository

type Service

type Service interface {

	// GetCurrentVersion reads a document from the database
	GetCurrentVersion(ctx context.Context, documentID []byte) (Model, error)

	// Exists checks if a document exists
	// Deprecated
	Exists(ctx context.Context, documentID []byte) bool

	// GetVersion reads a document from the database
	GetVersion(ctx context.Context, documentID []byte, version []byte) (Model, error)

	// DeriveFromCoreDocument derives a model given the core document.
	DeriveFromCoreDocument(cd coredocumentpb.CoreDocument) (Model, error)

	// CreateProofs creates proofs for the latest version document given the fields
	CreateProofs(ctx context.Context, documentID []byte, fields []string) (*DocumentProof, error)

	// CreateProofsForVersion creates proofs for a particular version of the document given the fields
	CreateProofsForVersion(ctx context.Context, documentID, version []byte, fields []string) (*DocumentProof, error)

	// RequestDocumentSignature Validates and Signs document received over the p2p layer
	RequestDocumentSignature(ctx context.Context, model Model, collaborator identity.DID) ([]*coredocumentpb.Signature, error)

	// ReceiveAnchoredDocument receives a new anchored document over the p2p layer, validates and updates the document in DB
	ReceiveAnchoredDocument(ctx context.Context, model Model, collaborator identity.DID) error

	// Create validates and persists Model and returns a Updated model
	// Deprecated
	Create(ctx context.Context, model Model) (Model, jobs.JobID, chan error, error)

	// Update validates and updates the model and return the updated model
	// Deprecated
	Update(ctx context.Context, model Model) (Model, jobs.JobID, chan error, error)

	// CreateModel creates a new model from the payload and initiates the anchor process.
	// Deprecated
	CreateModel(ctx context.Context, payload CreatePayload) (Model, jobs.JobID, error)

	// UpdateModel prepares the next version from the payload and initiates the anchor process.
	// Deprecated
	UpdateModel(ctx context.Context, payload UpdatePayload) (Model, jobs.JobID, error)

	// Derive derives the Model from the Payload.
	// If document_id is provided, it will prepare a new version of the document
	// Document Data will be patched from the old and attributes and collaborators are imported
	// If not provided, it is a fresh document.
	Derive(ctx context.Context, payload UpdatePayload) (Model, error)

	// DeriveClone derives the Model from the Payload, taking the provided template ID as the clone base
	DeriveClone(ctx context.Context, payload ClonePayload) (Model, error)

	// Commit triggers validations, state change and anchor job
	Commit(ctx context.Context, model Model) (jobs.JobID, error)

	// Validate takes care of document validation
	Validate(ctx context.Context, model Model, old Model) error

	// New returns a new uninitialised document.
	New(scheme string) (Model, error)
}

Service provides an interface for functions common to all document types

func DefaultService

func DefaultService(
	config Config,
	repo Repository,
	anchorSrv anchors.Service,
	registry *ServiceRegistry,
	idService identity.Service,
	queueSrv queue.TaskQueuer,
	jobManager jobs.Manager) Service

DefaultService returns the default implementation of the service

type ServiceRegistry

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

ServiceRegistry matches for a provided coreDocument the corresponding service

func NewServiceRegistry

func NewServiceRegistry() *ServiceRegistry

NewServiceRegistry returns a new instance of service registry

func (*ServiceRegistry) LocateService

func (s *ServiceRegistry) LocateService(serviceID string) (Service, error)

LocateService will return the registered service for the embedded document type

func (*ServiceRegistry) Register

func (s *ServiceRegistry) Register(serviceID string, service Service) error

Register can register a service which implements the ModelDeriver interface

type Signed added in v1.0.0

type Signed struct {
	Identity                                     identity.DID
	Type                                         AttributeType
	DocumentVersion, Value, Signature, PublicKey []byte
}

Signed is a custom attribute type with signature.

func (Signed) String added in v1.0.0

func (s Signed) String() string

String returns the hex value of the signature.

type Status added in v1.0.0

type Status string

Status represents the document status.

type TokenRegistry

type TokenRegistry interface {
	// OwnerOf to retrieve owner of the tokenID
	OwnerOf(registry common.Address, tokenID []byte) (common.Address, error)

	// OwnerOfWithRetrial to retrieve owner of the tokenID with retrial mechanism
	OwnerOfWithRetrial(registry common.Address, tokenID []byte) (common.Address, error)

	// CurrentIndexOfToken get the current index of the token
	CurrentIndexOfToken(registry common.Address, tokenID []byte) (*big.Int, error)
}

TokenRegistry defines NFT related functions.

type UpdatePayload added in v1.0.0

type UpdatePayload struct {
	CreatePayload
	DocumentID []byte
}

UpdatePayload holds the scheme, CollaboratorsAccess, Attributes, Data and document identifier.

type Validator

type Validator interface {
	// Validate validates the updates to the model in newState.
	Validate(oldState Model, newState Model) error
}

Validator is an interface every Validator (atomic or group) should implement

func CreateVersionValidator added in v1.0.0

func CreateVersionValidator(anchorSrv anchors.Service) Validator

CreateVersionValidator validates if the new core document is properly derived from old one

func LatestVersionValidator

func LatestVersionValidator(anchorSrv anchors.Service) Validator

LatestVersionValidator checks if the document is the latest version

func UpdateVersionValidator

func UpdateVersionValidator(anchorSrv anchors.Service) Validator

UpdateVersionValidator validates if the new core document is properly derived from old one

type ValidatorFunc

type ValidatorFunc func(old, new Model) error

ValidatorFunc implements Validator and can be used as a adaptor for functions with specific function signature

func (ValidatorFunc) Validate

func (vf ValidatorFunc) Validate(old, new Model) error

Validate passes the arguments to the underlying validator function and returns the results

type ValidatorGroup

type ValidatorGroup []Validator

ValidatorGroup implements Validator for validating a set of validators.

func PostAnchoredValidator

func PostAnchoredValidator(idService identity.Service, anchorSrv anchors.Service) ValidatorGroup

PostAnchoredValidator is a validator group with following validators PreAnchorValidator anchoredValidator should be called after anchoring the document/when received anchored document

func PreAnchorValidator

func PreAnchorValidator(idService identity.Service, anchorSrv anchors.Service) ValidatorGroup

PreAnchorValidator is a validator group with following validators base validator signing root validator document root validator signatures validator should be called before pre anchoring

func ReceivedAnchoredDocumentValidator

func ReceivedAnchoredDocumentValidator(
	idService identity.Service,
	anchorSrv anchors.Service,
	collaborator identity.DID) ValidatorGroup

ReceivedAnchoredDocumentValidator is a validator group with following validators transitionValidator PostAnchoredValidator

func RequestDocumentSignatureValidator

func RequestDocumentSignatureValidator(
	anchorSrv anchors.Service,
	idService identity.Service,
	collaborator identity.DID,
	anchorRepoAddress common.Address) ValidatorGroup

RequestDocumentSignatureValidator is a validator group with the following validators SignatureValidator transitionsValidator it should be called when a document is received over the p2p layer before signing

func SignatureValidator

func SignatureValidator(idService identity.Service, anchorSrv anchors.Service) ValidatorGroup

SignatureValidator is a validator group with following validators baseValidator signingRootValidator signaturesValidator should be called after sender signing the document, before requesting the document and after signature collection

func (ValidatorGroup) Validate

func (group ValidatorGroup) Validate(oldState Model, newState Model) (errs error)

Validate will execute all group specific atomic validations

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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