core

package
v0.0.6 Latest Latest
Warning

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

Go to latest
Published: Aug 12, 2024 License: MIT Imports: 49 Imported by: 1

Documentation

Index

Constants

View Source
const (
	// CreateFrom - Channel transference creation From
	CreateFrom typeOperation = iota
	// CreateTo - Channel transference creation To
	CreateTo
	// CancelFrom - cancellation in the From
	CancelFrom
)
View Source
const (
	// BalanceTokenLockedEvent - event on token balance locked
	BalanceTokenLockedEvent = "BalanceTokenLocked"
	// BalanceTokenUnlockedEvent - event on token balance unlocked
	BalanceTokenUnlockedEvent = "BalanceTokenUnlocked"
	// BalanceAllowedLockedEvent - event on allowed balance locked
	BalanceAllowedLockedEvent = "BalanceAllowedLocked"
	// BalanceAllowedUnlockedEvent - event on allowed balance unlocked
	BalanceAllowedUnlockedEvent = "BalanceAllowedUnlocked"
)
View Source
const (
	BatchExecute         = "batchExecute"
	SwapDone             = "swapDone"
	MultiSwapDone        = "multiSwapDone"
	CreateCCTransferTo   = "createCCTransferTo"
	DeleteCCTransferTo   = "deleteCCTransferTo"
	CommitCCTransferFrom = "commitCCTransferFrom"
	CancelCCTransferFrom = "cancelCCTransferFrom"
	DeleteCCTransferFrom = "deleteCCTransferFrom"
	CreateIndex          = "createIndex"
	ExecuteTasks         = "executeTasks"
)
View Source
const DocsKey = "documents"

DocsKey is a key for documents

View Source
const (
	// ErrMethodNotImplemented is the error message for not implemented methods
	ErrMethodNotImplemented = "method is not implemented for query"
)
View Source
const ExecuteTasksEvent = "executeTasks"
View Source
const (
	FnTransfer = "transfer"
)
View Source
const (
	LenTimeInMilliseconds = 13
)
View Source
const StateKeyNonce byte = 42 // hex: 2a

Variables

View Source
var (
	// ErrBigIntFromString - error on big int from string
	ErrBigIntFromString = errors.New("big int from string")
	// ErrPlatformAdminOnly - error on platform admin only
	ErrPlatformAdminOnly = errors.New("platform admin only")
	// ErrEmptyLockID - error on empty lock id
	ErrEmptyLockID = errors.New("empty lock id")
	// ErrReason - error on reason
	ErrReason = errors.New("empty reason")
	// ErrLockNotExists - error on lock not exists
	ErrLockNotExists = errors.New("lock not exists")
	// ErrAddressRequired - error on address required
	ErrAddressRequired = errors.New("address required")
	// ErrAmountRequired - error on amount required
	ErrAmountRequired = errors.New("amount required")
	// ErrTokenTickerRequired - error on token ticker required
	ErrTokenTickerRequired = errors.New("token ticker required")
	// ErrAlreadyExist - error on already exist
	ErrAlreadyExist = errors.New("lock already exist")
	// ErrInsufficientFunds - error on insufficient funds
	ErrInsufficientFunds    = errors.New("insufficient balance")
	ErrAdminNotSet          = errors.New("admin is not set in contract config")
	ErrUnauthorisedNotAdmin = errors.New("unauthorised, sender is not an admin")
)
View Source
var (
	ErrAmountMustBeGreaterThanZero = errors.New("amount must be greater than zero")
	ErrSameAddresses               = errors.New("from and to addresses must be different")
)
View Source
var (
	ErrSwapDisabled      = errors.New("swap is disabled")
	ErrMultiSwapDisabled = errors.New("multi-swap is disabled")
)
View Source
var ErrTasksNotFound = errors.New("no tasks found")

Functions

func AddDocs

func AddDocs(stub shim.ChaincodeStubInterface, rawDocs string) error

AddDocs adds documents to the ledger

func CheckSign

func CheckSign(
	stub shim.ChaincodeStubInterface,
	fn string,
	args []string,
	auth []string,
) (*types.Address, string, error)

CheckSign exists fo backward compatibility

func DeleteDoc

func DeleteDoc(stub shim.ChaincodeStubInterface, docID string) error

DeleteDoc deletes document from the ledger

func Logger deprecated

func Logger() *logging.Logger

Deprecated: added only for backward compatibility. This method was used by customers in chaincodes implementation. After customers change to the new logger from "github.com/anoideaopen/foundation/core/logger", this method will be deleted.

func OneOf added in v0.0.4

func OneOf(s string, ss ...string) bool

OneOf checks if a given string s is present within a slice of strings ss.

func TasksExecutorHandler added in v0.0.2

func TasksExecutorHandler(
	traceCtx telemetry.TraceContext,
	stub shim.ChaincodeStubInterface,
	cc *Chaincode,
) ([]byte, error)

TasksExecutorHandler executes multiple sub-transactions (tasks) within a single transaction in Hyperledger Fabric, using cached state between tasks to solve the MVCC problem. Each request in the arguments contains its own set of arguments for the respective chaincode method calls.

Types

type BaseContract

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

BaseContract is a base contract for all contracts

func (*BaseContract) AllowedBalanceAdd

func (bc *BaseContract) AllowedBalanceAdd(token string, address *types.Address, amount *big.Int, reason string) error

func (*BaseContract) AllowedBalanceBurnLocked

func (bc *BaseContract) AllowedBalanceBurnLocked(token string, address *types.Address, amount *big.Int, reason string) error

func (*BaseContract) AllowedBalanceGet

func (bc *BaseContract) AllowedBalanceGet(token string, address *types.Address) (*big.Int, error)

func (*BaseContract) AllowedBalanceGetAll

func (bc *BaseContract) AllowedBalanceGetAll(address *types.Address) (map[string]string, error)

func (*BaseContract) AllowedBalanceGetLocked added in v0.0.2

func (bc *BaseContract) AllowedBalanceGetLocked(token string, address *types.Address) (*big.Int, error)

func (*BaseContract) AllowedBalanceLock

func (bc *BaseContract) AllowedBalanceLock(token string, address *types.Address, amount *big.Int) error

func (*BaseContract) AllowedBalanceSub

func (bc *BaseContract) AllowedBalanceSub(token string, address *types.Address, amount *big.Int, reason string) error

func (*BaseContract) AllowedBalanceTransfer

func (bc *BaseContract) AllowedBalanceTransfer(token string, from *types.Address, to *types.Address, amount *big.Int, reason string) error

func (*BaseContract) AllowedBalanceTransferLocked

func (bc *BaseContract) AllowedBalanceTransferLocked(token string, from *types.Address, to *types.Address, amount *big.Int, reason string) error

func (*BaseContract) AllowedBalanceUnLock

func (bc *BaseContract) AllowedBalanceUnLock(token string, address *types.Address, amount *big.Int) error

func (*BaseContract) AllowedIndustrialBalanceAdd

func (bc *BaseContract) AllowedIndustrialBalanceAdd(address *types.Address, industrialAssets []*pb.Asset, reason string) error

func (*BaseContract) AllowedIndustrialBalanceSub

func (bc *BaseContract) AllowedIndustrialBalanceSub(address *types.Address, industrialAssets []*pb.Asset, reason string) error

func (*BaseContract) AllowedIndustrialBalanceTransfer

func (bc *BaseContract) AllowedIndustrialBalanceTransfer(from *types.Address, to *types.Address, industrialAssets []*pb.Asset, reason string) error

func (*BaseContract) ApplyContractConfig

func (bc *BaseContract) ApplyContractConfig(config *pb.ContractConfig) error

func (*BaseContract) ContractConfig

func (bc *BaseContract) ContractConfig() *pb.ContractConfig

func (*BaseContract) GetID

func (bc *BaseContract) GetID() string

func (*BaseContract) GetMethods

func (bc *BaseContract) GetMethods(bci BaseContractInterface) []string

GetMethods returns list of methods

func (*BaseContract) GetStub

GetStub returns stub

func (*BaseContract) GetTraceContext

func (bc *BaseContract) GetTraceContext() telemetry.TraceContext

GetTraceContext returns trace context. Using for call methods only

func (*BaseContract) IndustrialBalanceAdd

func (bc *BaseContract) IndustrialBalanceAdd(token string, address *types.Address, amount *big.Int, reason string) error

func (*BaseContract) IndustrialBalanceBurnLocked

func (bc *BaseContract) IndustrialBalanceBurnLocked(token string, address *types.Address, amount *big.Int, reason string) error

func (*BaseContract) IndustrialBalanceGet

func (bc *BaseContract) IndustrialBalanceGet(address *types.Address) (map[string]string, error)

func (*BaseContract) IndustrialBalanceGetLocked

func (bc *BaseContract) IndustrialBalanceGetLocked(address *types.Address) (map[string]string, error)

func (*BaseContract) IndustrialBalanceLock

func (bc *BaseContract) IndustrialBalanceLock(token string, address *types.Address, amount *big.Int) error

func (*BaseContract) IndustrialBalanceSub

func (bc *BaseContract) IndustrialBalanceSub(token string, address *types.Address, amount *big.Int, reason string) error

func (*BaseContract) IndustrialBalanceTransfer

func (bc *BaseContract) IndustrialBalanceTransfer(token string, from *types.Address, to *types.Address, amount *big.Int, reason string) error

func (*BaseContract) IndustrialBalanceTransferLocked

func (bc *BaseContract) IndustrialBalanceTransferLocked(token string, from *types.Address, to *types.Address, amount *big.Int, reason string) error

func (*BaseContract) IndustrialBalanceUnLock

func (bc *BaseContract) IndustrialBalanceUnLock(token string, address *types.Address, amount *big.Int) error

func (*BaseContract) IsService added in v0.0.3

func (bc *BaseContract) IsService() bool

IsService returns true if chaincode runs as a service

func (*BaseContract) NBTxCommitCCTransferFrom

func (bc *BaseContract) NBTxCommitCCTransferFrom(id string) error

NBTxCommitCCTransferFrom - transaction writes the commit flag in the transfer in the From channel. Executed after successful creation of a mating part in the channel To (TxCreateCCTransferTo) This transaction is sent only by the channel-transfer service with a "robot" certificate

func (*BaseContract) NBTxDeleteCCTransferFrom

func (bc *BaseContract) NBTxDeleteCCTransferFrom(id string) error

NBTxDeleteCCTransferFrom - transaction deletes the transfer record in the channel From. Performed after successful removal in the canal To (NBTxDeleteCCTransferTo) This transaction is sent only by the channel-transfer service with a "robot" certificate

func (*BaseContract) NBTxDeleteCCTransferTo

func (bc *BaseContract) NBTxDeleteCCTransferTo(id string) error

NBTxDeleteCCTransferTo - transaction deletes transfer record in channel To. Executed after a successful commit in the From channel (NBTxCommitCCTransferFrom) This transaction is sent only by the channel-transfer service with a "robot" certificate

func (*BaseContract) NBTxHealthCheckNb

func (bc *BaseContract) NBTxHealthCheckNb(_ *types.Sender) error

NBTxHealthCheckNb - the same but not batched

func (*BaseContract) QueryBuildInfo

func (bc *BaseContract) QueryBuildInfo() (*debug.BuildInfo, error)

QueryBuildInfo returns debug.BuildInfo struct with build information, stored in binary file or error if it is occurs

func (*BaseContract) QueryChannelTransferFrom

func (bc *BaseContract) QueryChannelTransferFrom(id string) (*pb.CCTransfer, error)

QueryChannelTransferFrom - receiving a transfer record from the channel From

func (*BaseContract) QueryChannelTransferTo

func (bc *BaseContract) QueryChannelTransferTo(id string) (*pb.CCTransfer, error)

QueryChannelTransferTo - receiving a transfer record from the channel To

func (*BaseContract) QueryChannelTransfersFrom

func (bc *BaseContract) QueryChannelTransfersFrom(pageSize int64, bookmark string) (*pb.CCTransfers, error)

QueryChannelTransfersFrom - getting all transfer records from the channel From You can receive them in parts (chunks)

func (*BaseContract) QueryCoreChaincodeIDName

func (bc *BaseContract) QueryCoreChaincodeIDName() (string, error)

QueryCoreChaincodeIDName returns CORE_CHAINCODE_ID_NAME

func (*BaseContract) QueryGetLockedAllowedBalance

func (bc *BaseContract) QueryGetLockedAllowedBalance(
	lockID string,
) (*proto.AllowedBalanceLock, error)

QueryGetLockedAllowedBalance - returns the existing blocking of the allowedbalance AllowedBalanceLock

func (*BaseContract) QueryGetLockedTokenBalance

func (bc *BaseContract) QueryGetLockedTokenBalance(
	lockID string,
) (*proto.TokenBalanceLock, error)

QueryGetLockedTokenBalance - returns an existing balance token lock TokenBalanceLock

func (*BaseContract) QueryGetNonce

func (bc *BaseContract) QueryGetNonce(owner *types.Address) (string, error)

func (*BaseContract) QueryGroupBalanceOf

func (bc *BaseContract) QueryGroupBalanceOf(address *types.Address) (map[string]string, error)

QueryGroupBalanceOf - returns balance of the token for user address

func (*BaseContract) QueryMultiSwapGet

func (bc *BaseContract) QueryMultiSwapGet(swapID string) (*proto.MultiSwap, error)

QueryMultiSwapGet - returns multiswap by id

func (*BaseContract) QueryNameOfFiles

func (bc *BaseContract) QueryNameOfFiles() ([]string, error)

QueryNameOfFiles returns list path/name of embed files

func (*BaseContract) QuerySrcFile

func (bc *BaseContract) QuerySrcFile(name string) (string, error)

QuerySrcFile returns file

func (*BaseContract) QuerySrcPartFile

func (bc *BaseContract) QuerySrcPartFile(name string, start int, end int) (string, error)

QuerySrcPartFile returns part of file start - include end - exclude

func (*BaseContract) QuerySwapGet

func (bc *BaseContract) QuerySwapGet(swapID string) (*proto.Swap, error)

QuerySwapGet returns swap by id

func (*BaseContract) QuerySystemEnv

func (bc *BaseContract) QuerySystemEnv() (map[string]string, error)

QuerySystemEnv returns system environment

func (*BaseContract) Router added in v0.0.3

func (bc *BaseContract) Router() routing.Router

func (*BaseContract) TokenBalanceAdd

func (bc *BaseContract) TokenBalanceAdd(address *types.Address, amount *big.Int, reason string) error

func (*BaseContract) TokenBalanceAddWithReason added in v0.0.3

func (bc *BaseContract) TokenBalanceAddWithReason(address *types.Address, amount *big.Int, reason string) error

func (*BaseContract) TokenBalanceAddWithTicker

func (bc *BaseContract) TokenBalanceAddWithTicker(address *types.Address, amount *big.Int, ticker string, reason string) error

func (*BaseContract) TokenBalanceBurnLocked

func (bc *BaseContract) TokenBalanceBurnLocked(address *types.Address, amount *big.Int, reason string) error

func (*BaseContract) TokenBalanceGet

func (bc *BaseContract) TokenBalanceGet(address *types.Address) (*big.Int, error)

func (*BaseContract) TokenBalanceGetLocked

func (bc *BaseContract) TokenBalanceGetLocked(address *types.Address) (*big.Int, error)

func (*BaseContract) TokenBalanceLock

func (bc *BaseContract) TokenBalanceLock(address *types.Address, amount *big.Int) error

func (*BaseContract) TokenBalanceSub

func (bc *BaseContract) TokenBalanceSub(address *types.Address, amount *big.Int, reason string) error

func (*BaseContract) TokenBalanceSubWithTicker

func (bc *BaseContract) TokenBalanceSubWithTicker(address *types.Address, amount *big.Int, ticker string, reason string) error

func (*BaseContract) TokenBalanceTransfer

func (bc *BaseContract) TokenBalanceTransfer(from *types.Address, to *types.Address, amount *big.Int, reason string) error

func (*BaseContract) TokenBalanceTransferLocked

func (bc *BaseContract) TokenBalanceTransferLocked(from *types.Address, to *types.Address, amount *big.Int, reason string) error

func (*BaseContract) TokenBalanceUnlock

func (bc *BaseContract) TokenBalanceUnlock(address *types.Address, amount *big.Int) error

func (*BaseContract) TracingHandler

func (bc *BaseContract) TracingHandler() *telemetry.TracingHandler

TracingHandler returns base contract tracingHandler

func (*BaseContract) TxCancelCCTransferFrom

func (bc *BaseContract) TxCancelCCTransferFrom(id string) error

TxCancelCCTransferFrom - transaction cancels (deletes) the transfer record in the From channel returns balances to the user. If the service cannot create a response part in the "To" channel within some timeout, it is required to cancel the transfer. After TxChannelTransferByAdmin or TxChannelTransferByCustomer This transaction is sent only by the channel-transfer service with a "robot" certificate

func (*BaseContract) TxChannelMultiTransferByAdmin added in v0.0.6

func (bc *BaseContract) TxChannelMultiTransferByAdmin(
	sender *types.Sender,
	idTransfer string,
	to string,
	idUser *types.Address,
	items []TransferItem,
) (string, error)

TxChannelMultiTransferByAdmin - transaction initiating transfer between channels. Signed by the channel admin (site). The tokens are transferred from idUser to the same user. After the checks, a transfer record is created and the user's balances are reduced.

func (*BaseContract) TxChannelMultiTransferByCustomer added in v0.0.6

func (bc *BaseContract) TxChannelMultiTransferByCustomer(
	sender *types.Sender,
	idTransfer string,
	to string,
	items []TransferItem,
) (string, error)

TxChannelMultiTransferByCustomer - transaction initiating transfer between channels. The owner of tokens signs. Tokens are transferred to themselveselves. After the checks, a transfer record is created and the user's balances are reduced.

func (*BaseContract) TxChannelTransferByAdmin

func (bc *BaseContract) TxChannelTransferByAdmin(
	sender *types.Sender,
	idTransfer string,
	to string,
	idUser *types.Address,
	token string,
	amount *big.Int,
) (string, error)

TxChannelTransferByAdmin - transaction initiating transfer between channels. Signed by the channel admin (site). The tokens are transferred from idUser to the same user. After the checks, a transfer record is created and the user's balances are reduced.

func (*BaseContract) TxChannelTransferByCustomer

func (bc *BaseContract) TxChannelTransferByCustomer(
	sender *types.Sender,
	idTransfer string,
	to string,
	token string,
	amount *big.Int,
) (string, error)

TxChannelTransferByCustomer - transaction initiating transfer between channels. The owner of tokens signs. Tokens are transferred to themselveselves. After the checks, a transfer record is created and the user's balances are reduced.

func (*BaseContract) TxCreateCCTransferTo

func (bc *BaseContract) TxCreateCCTransferTo(dataIn string) (string, error)

TxCreateCCTransferTo - transaction creates a transfer (already with commit sign) in the channel To and increases the user's balances. The transaction must be executed after the initiating transfer transaction (TxChannelTransferByAdmin or TxChannelTransferByCustomer). This transaction is sent only by the channel-transfer service with a "robot" certificate

func (*BaseContract) TxHealthCheck

func (bc *BaseContract) TxHealthCheck(_ *types.Sender) error

TxHealthCheck can be called by an administrator of the contract for checking if the business logic of the chaincode is still alive.

func (*BaseContract) TxLockAllowedBalance

func (bc *BaseContract) TxLockAllowedBalance(
	sender *types.Sender,
	req *proto.BalanceLockRequest,
) error

TxLockAllowedBalance - blocks tokens on the user's allowedbalance method calls the chaincode admin, the input is a BalanceLockRequest

func (*BaseContract) TxLockTokenBalance

func (bc *BaseContract) TxLockTokenBalance(
	sender *types.Sender,
	req *proto.BalanceLockRequest,
) error

TxLockTokenBalance - blocks tokens on the user's token balance method is called by the chaincode admin, the input is BalanceLockRequest

func (*BaseContract) TxMultiSwapBegin

func (bc *BaseContract) TxMultiSwapBegin(sender *types.Sender, token string, multiSwapAssets types.MultiSwapAssets, contractTo string, hash types.Hex) (string, error)

TxMultiSwapBegin - creates multiswap

func (*BaseContract) TxMultiSwapCancel

func (bc *BaseContract) TxMultiSwapCancel(sender *types.Sender, swapID string) error

TxMultiSwapCancel - cancels multiswap

func (*BaseContract) TxSwapBegin

func (bc *BaseContract) TxSwapBegin(
	sender *types.Sender,
	token string,
	contractTo string,
	amount *big.Int,
	hash types.Hex,
) (string, error)

TxSwapBegin creates swap

func (*BaseContract) TxSwapCancel

func (bc *BaseContract) TxSwapCancel(_ *types.Sender, swapID string) error

TxSwapCancel cancels swap

func (*BaseContract) TxTransferBalance added in v0.0.3

func (bc *BaseContract) TxTransferBalance(
	sender *types.Sender,
	req *proto.TransferRequest,
) error

TxTransferBalance - transfer balance from one address to another address by the chaincode admin, the input is TransferRequest.

func (*BaseContract) TxUnlockAllowedBalance

func (bc *BaseContract) TxUnlockAllowedBalance(
	sender *types.Sender,
	req *proto.BalanceLockRequest,
) error

TxUnlockAllowedBalance - unblocks (fully or partially) tokens on the user's allowedbalance method calls the chaincode admin, the input is a BalanceLockRequest

func (*BaseContract) TxUnlockTokenBalance

func (bc *BaseContract) TxUnlockTokenBalance(
	sender *types.Sender,
	req *proto.BalanceLockRequest,
) error

TxUnlockTokenBalance - unblocks (fully or partially) tokens on the user's token balance method is called by the chaincode admin, the input is BalanceLockRequest

func (*BaseContract) ValidateConfig

func (bc *BaseContract) ValidateConfig(config []byte) error

type BaseContractInterface

type BaseContractInterface interface {
	config.Configurator

	// ------------------------------------------------------------------
	GetID() string

	TokenBalanceTransfer(from *types.Address, to *types.Address, amount *big.Int, reason string) error
	AllowedBalanceTransfer(token string, from *types.Address, to *types.Address, amount *big.Int, reason string) error

	TokenBalanceGet(address *types.Address) (*big.Int, error)
	TokenBalanceAdd(address *types.Address, amount *big.Int, reason string) error
	TokenBalanceSub(address *types.Address, amount *big.Int, reason string) error

	TokenBalanceAddWithTicker(address *types.Address, amount *big.Int, ticker string, reason string) error
	TokenBalanceSubWithTicker(address *types.Address, amount *big.Int, ticker string, reason string) error

	AllowedBalanceGet(token string, address *types.Address) (*big.Int, error)
	AllowedBalanceAdd(token string, address *types.Address, amount *big.Int, reason string) error
	AllowedBalanceSub(token string, address *types.Address, amount *big.Int, reason string) error

	AllowedBalanceGetAll(address *types.Address) (map[string]string, error)

	IndustrialBalanceGet(address *types.Address) (map[string]string, error)
	IndustrialBalanceTransfer(token string, from *types.Address, to *types.Address, amount *big.Int, reason string) error
	IndustrialBalanceAdd(token string, address *types.Address, amount *big.Int, reason string) error
	IndustrialBalanceSub(token string, address *types.Address, amount *big.Int, reason string) error

	AllowedIndustrialBalanceAdd(address *types.Address, industrialAssets []*pb.Asset, reason string) error
	AllowedIndustrialBalanceSub(address *types.Address, industrialAssets []*pb.Asset, reason string) error
	AllowedIndustrialBalanceTransfer(from *types.Address, to *types.Address, industrialAssets []*pb.Asset, reason string) error

	IsService() bool

	TracingHandler() *telemetry.TracingHandler

	Router() routing.Router

	GetTraceContext() telemetry.TraceContext
	GetStub() shim.ChaincodeStubInterface
	// contains filtered or unexported methods
}

BaseContractInterface represents BaseContract interface

type Chaincode added in v0.0.2

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

Chaincode defines the structure for a chaincode instance, with methods, configuration, and options for transaction processing.

func NewCC

func NewCC(
	cc BaseContractInterface,
	chOptions ...ChaincodeOption,
) (*Chaincode, error)

NewCC creates a new instance of ChainCode with the given contract interface and configurable options. It initializes the ChainCode instance with the provided BaseContractInterface and applies advanced configuration settings through a combination of ChaincodeOption functions and environmental variables.

The environmental variables are checked first to configure TLS settings, which takes precedence over the settings provided by the ChaincodeOption functions. The function will configure TLS if the respective environment variables contain the necessary information. These variables are:

- CHAINCODE_TLS_KEY or CHAINCODE_TLS_KEY_FILE: For the private key in PEM format or file path. - CHAINCODE_TLS_CERT or CHAINCODE_TLS_CERT_FILE: For the public key certificate in PEM format or file path. - CHAINCODE_TLS_CLIENT_CA_CERTS or CHAINCODE_TLS_CLIENT_CA_CERTS_FILE: For the client CA certificates in PEM format or file path.

If the environment variables do not provide the TLS configuration, the function will fall back to the configuration provided by ChaincodeOption functions, such as WithTLS or WithTLSFromFiles. If neither are provided, the TLS feature will remain disabled in the chaincode configuration.

Args: cc: The BaseContractInterface which encapsulates the contract logic that the ChainCode will execute.

options: ContractOptions is a pointer to the configuration settings that will be applied to the chaincode. The settings within options allow for fine-tuned control of the chaincode's behavior, such as transaction TTL, batching prefixes, and swap behavior. If this parameter is not needed, it can be omitted or set to nil.

chOptions: A variadic number of ChaincodeOption function types which are used to apply specific configurations to the chaincodeOptions structure. These options may include configurations that can be overridden by environmental variables, particularly for TLS.

Returns: A pointer to a ChainCode instance and an error. An error is non-nil if there is a failure in applying the provided ChaincodeOption functions, or if there is an issue with reading and processing the environmental variables for the TLS configuration.

Example usage:

tlsConfig := &core.TLS{ /* ... */ }
cc, err := core.NewCC(contract, contractOptions, core.WithTLS(tlsConfig))
if err != nil {
	// Handle error
}

In the above example, tlsConfig provided by WithTLS will be overridden if the corresponding environmental variables for TLS configuration are set.

func (*Chaincode) BatchHandler added in v0.0.2

func (cc *Chaincode) BatchHandler(traceCtx telemetry.TraceContext, stub shim.ChaincodeStubInterface) peer.Response

BatchHandler handles the batching logic for chaincode invocations.

func (*Chaincode) Init added in v0.0.2

Init is called during chaincode instantiation to initialize any data. Note that upgrade also calls this function to reset or to migrate data.

func (*Chaincode) Invoke added in v0.0.2

func (cc *Chaincode) Invoke(stub shim.ChaincodeStubInterface) (r peer.Response)

Invoke is called to update or query the ledger in a proposal transaction. Given the function name, it delegates the execution to the respective handler.

func (*Chaincode) InvokeContractMethod added in v0.0.2

func (cc *Chaincode) InvokeContractMethod(
	traceCtx telemetry.TraceContext,
	stub shim.ChaincodeStubInterface,
	sender *proto.Address,
	method string,
	args []string,
) ([]byte, error)

InvokeContractMethod calls a Chaincode contract method, processes the arguments, and returns the result as bytes.

func (*Chaincode) PrependSender added in v0.0.2

func (cc *Chaincode) PrependSender(method string, sender *proto.Address, args []string) []string

func (*Chaincode) Router added in v0.0.2

func (cc *Chaincode) Router() routing.Router

Router returns the contract router for the Chaincode.

func (*Chaincode) Start added in v0.0.2

func (cc *Chaincode) Start() error

Start begins the chaincode execution based on the environment configuration. It decides whether to start the chaincode in the default mode or as a server based on the CHAINCODE_EXEC_MODE environment variable. In server mode, it requires the CHAINCODE_ID to be set and uses CHAINCODE_SERVER_PORT for the port or defaults to a predefined port if not set. It returns an error if the necessary environment variables are not set or if the chaincode fails to start.

func (*Chaincode) ValidateTxID added in v0.0.2

func (cc *Chaincode) ValidateTxID(stub shim.ChaincodeStubInterface) error

ValidateTxID validates the transaction ID to ensure it is correctly formatted.

Args: stub: The shim.ChaincodeStubInterface to access the transaction ID.

Returns: - nil if the transaction ID is valid. - An error if the transaction ID is not valid hexadecimal.

type ChaincodeOption

type ChaincodeOption func(opts *chaincodeOptions) error

ChaincodeOption represents a function that applies configuration options to a chaincodeOptions object.

func WithConfigMapper added in v0.0.2

func WithConfigMapper(cm config.ConfigMapper) ChaincodeOption

WithConfigMapper is a ChaincodeOption that specifies the ConfigMapper for the ChainCode.

func WithConfigMapperFunc added in v0.0.2

func WithConfigMapperFunc(cmf config.ConfigMapperFunc) ChaincodeOption

WithConfigMapperFunc is a ChaincodeOption that specifies the ConfigMapper for the ChainCode.

cmf: A function implementing the ConfigMapper interface.

It returns a ChaincodeOption that sets the ConfigMapper field in the chaincodeOptions.

Example using FromArgsWithAdmin:

chaincode := core.NewCC(cc, core.WithConfigMapperFunc(func(args []string) (*proto.Config, error) {
    return config.FromArgsWithAdmin("ndm", args)
}))

Example with manual mapping:

chaincode := core.NewCC(cc, core.WithConfigMapperFunc(func(args []string) (*proto.Config, error) {
    const requiredArgsCount = 4
    if len(args) != requiredArgsCount {
        return nil, fmt.Errorf("required args length is '%d', passed %d", requiredArgsCount, len(args))
    }
    robotSKI := args[1]
    if robotSKI == "" {
        return nil, fmt.Errorf("robot ski is empty")
    }
    issuerAddress := args[2]
    if issuerAddress == "" {
        return nil, fmt.Errorf("issuer address is empty")
    }
    adminAddress := args[3]
    if adminAddress == "" {
        return nil, fmt.Errorf("admin address is empty")
    }
    return &proto.Config{
        Contract: &proto.ContractConfig{
            Symbol: "TT",
            Admin:  &proto.Wallet{Address: adminAddress},
            RobotSKI: robotSKI,
        },
        Token: &proto.TokenConfig{
            Name: "Test Token",
            Issuer: &proto.Wallet{Address: issuerAddress},
        },
    }, nil
}))

func WithRouter added in v0.0.3

func WithRouter(router routing.Router) ChaincodeOption

WithRouter returns a ChaincodeOption function that sets the router in the chaincode options.

func WithRouters added in v0.0.4

func WithRouters(routers ...routing.Router) ChaincodeOption

WithRouters returns a ChaincodeOption function that sets the router in the chaincode options.

func WithSrcFS

func WithSrcFS(fs *embed.FS) ChaincodeOption

WithSrcFS is a ChaincodeOption that specifies the source file system to be used by the ChainCode.

func WithTLS

func WithTLS(tls *TLS) ChaincodeOption

WithTLS is a ChaincodeOption that specifies the TLS configuration for the ChainCode.

func WithTLSFromFiles

func WithTLSFromFiles(keyPath, certPath, clientCACertPath string) (ChaincodeOption, error)

WithTLSFromFiles returns a ChaincodeOption that sets the TLS configuration for the ChainCode from provided file paths. It reads the specified files and uses their contents to configure TLS for the chaincode.

keyPath: A string representing the file path to the TLS private key.

certPath: A string representing the file path to the TLS public certificate.

clientCACertPath: An optional string representing the file path to the client CA certificate. If no client CA certificate is needed, this can be left empty.

It returns a ChaincodeOption or an error if reading any of the files fails.

Example:

tlsOpt, err := core.WithTLSFromFiles("tls/key.pem", "tls/cert.pem", "tls/ca.pem")
if err != nil {
    log.Fatalf("Error configuring TLS: %v", err)
}
cc, err := core.NewCC(contractInstance, contractOptions, tlsOpt)
if err != nil {
    log.Fatalf("Error creating new chaincode instance: %v", err)
}

This example sets up the chaincode TLS configuration using the key, certificate, and CA certificate files located in the "tls" directory. After obtaining the ChaincodeOption from WithTLSFromFiles, it is passed to NewCC to create a new instance of ChainCode with TLS enabled.

type Doc

type Doc struct {
	ID   string `json:"id"`
	Hash string `json:"hash"`
}

Doc json struct

func DocumentsList

func DocumentsList(stub shim.ChaincodeStubInterface) ([]Doc, error)

DocumentsList returns list of documents

type TLS

type TLS struct {
	Key           []byte // Private key for TLS authentication.
	Cert          []byte // Public certificate for TLS authentication.
	ClientCACerts []byte // Optional client CA certificates for verifying connecting peers.
}

TLS holds the key and certificate data for TLS communication, as well as client CA certificates for peer verification if needed.

type TaskExecutor added in v0.0.2

type TaskExecutor struct {
	BatchCacheStub *cachestub.BatchCacheStub
	Chaincode      *Chaincode
	SKI            string
	TracingHandler *telemetry.TracingHandler
}

TaskExecutor handles the execution of a group of tasks.

func NewTaskExecutor added in v0.0.2

func NewTaskExecutor(stub shim.ChaincodeStubInterface, cc *Chaincode, tracingHandler *telemetry.TracingHandler) *TaskExecutor

NewTaskExecutor initializes a new TaskExecutor.

func (*TaskExecutor) ExecuteTask added in v0.0.2

func (e *TaskExecutor) ExecuteTask(
	traceCtx telemetry.TraceContext,
	task *proto.Task,
	stub *cachestub.BatchCacheStub,
) (*proto.TxResponse, *proto.BatchTxEvent)

ExecuteTask processes an individual task, returning a transaction response and event.

func (*TaskExecutor) ExecuteTasks added in v0.0.2

func (e *TaskExecutor) ExecuteTasks(
	traceCtx telemetry.TraceContext,
	tasks []*proto.Task,
) (*proto.BatchResponse, *proto.BatchEvent, error)

ExecuteTasks processes a group of tasks, returning a group response and event.

type TransferItem added in v0.0.6

type TransferItem struct {
	Token  string   `json:"token"`
	Amount *big.Int `json:"amount"`
}

type TxResponse

type TxResponse struct {
	Method     string                    `json:"method"`
	Error      string                    `json:"error,omitempty"`
	Result     string                    `json:"result"`
	Events     map[string][]byte         `json:"events,omitempty"`
	Accounting []*proto.AccountingRecord `json:"accounting"`
}

Directories

Path Synopsis
Package routing defines the Router interface for managing smart contract method calls.
Package routing defines the Router interface for managing smart contract method calls.
grpc
Package grpc provides a GRPC-based router for smart contract method invocation.
Package grpc provides a GRPC-based router for smart contract method invocation.
mux
Package mux provides a multiplexer (or router) that allows multiple github.com/anoideaopen/foundation/core/routing.Router instances to be used together.
Package mux provides a multiplexer (or router) that allows multiple github.com/anoideaopen/foundation/core/routing.Router instances to be used together.
reflect
Package reflect provides functionality for routing smart contract method calls using Go reflection.
Package reflect provides functionality for routing smart contract method calls using Go reflection.
big

Jump to

Keyboard shortcuts

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