From c30e3623c51b2e3c8e1fc6cac3b7bb1763cba98f Mon Sep 17 00:00:00 2001 From: simon yi Date: Wed, 21 Sep 2022 18:00:17 +0800 Subject: [PATCH] =?UTF-8?q?=E6=A0=BC=E5=BC=8F=E5=8C=96=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- sdk/adt/array.go | 5 +- sdk/cases/network.go | 5 +- sdk/crypto.go | 2 +- sdk/ferrors/error.go | 14 +-- sdk/ipld.go | 2 +- sdk/shim/shim.go | 4 +- sdk/sself.go | 2 - sdk/sys/abort_call.go | 13 +-- sdk/sys/actor_call.go | 72 +++++++------ sdk/sys/context_call.go | 11 +- sdk/sys/crypto_call.go | 181 ++++++++++++++++---------------- sdk/sys/debug_call.go | 8 +- sdk/sys/gas_call.go | 27 ++--- sdk/sys/ipld_call.go | 187 +++++++++++++++++----------------- sdk/sys/network_call.go | 22 ++-- sdk/sys/rand_call.go | 66 ++++++------ sdk/sys/send_call.go | 57 ++++++----- sdk/sys/simulated/doc.go | 2 + sdk/sys/simulated/error.go | 10 +- sdk/sys/simulated/opration.go | 2 + sdk/sys/simulated/options.go | 13 +-- sdk/sys/simulated/state.go | 25 +++-- sdk/sys/simulated/utils.go | 17 ++-- sdk/sys/sself_call.go | 72 ++++++------- sdk/types/fvm_token_amount.go | 15 ++- sdk/utils.go | 2 +- 26 files changed, 439 insertions(+), 397 deletions(-) create mode 100644 sdk/sys/simulated/doc.go diff --git a/sdk/adt/array.go b/sdk/adt/array.go index 0fdb509..e6a3069 100644 --- a/sdk/adt/array.go +++ b/sdk/adt/array.go @@ -11,7 +11,7 @@ import ( cbg "github.com/whyrusleeping/cbor-gen" ) -//DefaultAmtOptions default amt option +// DefaultAmtOptions default amt option var DefaultAmtOptions = []amt.Option{} // Array stores a sparse sequence of values in an AMT. @@ -129,7 +129,8 @@ func (a *Array) Length() uint64 { } // Get retrieves array element into the 'out' unmarshaler, returning a boolean -// indicating whether the element was found in the array +// +// indicating whether the element was found in the array func (a *Array) Get(k uint64, out cbor.Unmarshaler) (bool, error) { if found, err := a.root.Get(a.store.Context(), k, out); err != nil { return false, fmt.Errorf("failed to get index %v in root %v: %w", k, a.root, err) diff --git a/sdk/cases/network.go b/sdk/cases/network.go index 13e9aa0..ee8c8f6 100644 --- a/sdk/cases/network.go +++ b/sdk/cases/network.go @@ -1,3 +1,4 @@ +//nolint:param package main import ( @@ -23,10 +24,10 @@ func Invoke(_ uint32) uint32 { //nolint fee, err := sdk.BaseFee() assert.Nil(t, err) - assert.Equal(t, "100", fee.Big().String()) + assert.Equal(t, "100", fee.String()) value, err := sdk.TotalFilCircSupply() assert.Nil(t, err) - assert.Equal(t, "2000000000000000000000000000", value.Big().String()) + assert.Equal(t, "2000000000000000000000000000", value.String()) return 0 } diff --git a/sdk/crypto.go b/sdk/crypto.go index 1d941a4..4676d32 100644 --- a/sdk/crypto.go +++ b/sdk/crypto.go @@ -38,7 +38,7 @@ func VerifySeal(info *proof.SealVerifyInfo) (bool, error) { return sys.VerifySeal(info) } -//VerifyPost verifies a sector seal proof. +// VerifyPost verifies a sector seal proof. func VerifyPost(info *proof.WindowPoStVerifyInfo) (bool, error) { return sys.VerifyPost(info) } diff --git a/sdk/ferrors/error.go b/sdk/ferrors/error.go index 944741c..6cd8852 100644 --- a/sdk/ferrors/error.go +++ b/sdk/ferrors/error.go @@ -8,12 +8,12 @@ import ( // ExitCode define error in fvm and custom actor type ExitCode uint32 -//Error return error message of exitcode +// Error return error message of exitcode func (e ExitCode) Error() string { return fmt.Sprintf("%d", e) } -//Is check whether error is exitcode +// Is check whether error is exitcode func (e ExitCode) Is(code error) bool { return e == code } @@ -23,7 +23,7 @@ func (e ExitCode) IsSystemError() bool { return uint32(e) < FIRST_USER_EXIT_CODE } -//nolint +// nolint const ( // Exit codes which originate inside the VM. // These values may not be used by actors when aborting. @@ -90,23 +90,23 @@ const ( // RESERVED_31 ExitCode = 31 ) -//FvmError fvm error include error code and error message +// FvmError fvm error include error code and error message type FvmError struct { code ExitCode message string } -//NewFvmError new fvm error from error code and message +// NewFvmError new fvm error from error code and message func NewFvmError(code ExitCode, msg string) FvmError { return FvmError{code, msg} } -//Error return error message for fvm error +// Error return error message for fvm error func (fvmError FvmError) Error() string { return fmt.Sprintf("%s %d", fvmError.message, fvmError.code) } -//Unwrap return inner error code +// Unwrap return inner error code func (fvmError FvmError) Unwrap() error { return fvmError.code } diff --git a/sdk/ipld.go b/sdk/ipld.go index 15c9060..e143cbb 100644 --- a/sdk/ipld.go +++ b/sdk/ipld.go @@ -55,7 +55,7 @@ func GetBlock(id types.BlockID, size *uint32) ([]byte, error) { if err != nil { return nil, err } - + if remaining > 0 { //more than 1KiB sencondPart, remaining, err := sys.Read(id, uint32(len(block)), remaining) //only set len and slice if err != nil { diff --git a/sdk/shim/shim.go b/sdk/shim/shim.go index e9472e0..a06984b 100644 --- a/sdk/shim/shim.go +++ b/sdk/shim/shim.go @@ -1,10 +1,12 @@ +//nolint:param package main import ( "unsafe" ) -/// Logs a message on the node. +// Logs a message on the node. +// //go:wasm-module debug //export log func debugLog(message uintptr, message_len uint32) uint32 //nolint diff --git a/sdk/sself.go b/sdk/sself.go index 4966fa0..54a075d 100644 --- a/sdk/sself.go +++ b/sdk/sself.go @@ -1,8 +1,6 @@ package sdk import ( - - addr "github.com/filecoin-project/go-address" "github.com/ipfs-force-community/go-fvm-sdk/sdk/sys" "github.com/ipfs-force-community/go-fvm-sdk/sdk/types" diff --git a/sdk/sys/abort_call.go b/sdk/sys/abort_call.go index cb6a1b1..190e3e1 100644 --- a/sdk/sys/abort_call.go +++ b/sdk/sys/abort_call.go @@ -3,12 +3,13 @@ package sys -/// Abort execution with the given code and message. The code is recorded in the receipt, the -/// message is for debugging only. -/// -/// # Errors -/// -/// None. This function doesn't return. +// / Abort execution with the given code and message. The code is recorded in the receipt, the +// / message is for debugging only. +// / +// / # Errors +// / +// / None. This function doesn't return. +// //go:wasm-module vm //export abort func vmAbort(code uint32, msgOff uintptr, msgLen uint32) uint32 diff --git a/sdk/sys/actor_call.go b/sdk/sys/actor_call.go index 2aa5fda..7e90871 100644 --- a/sdk/sys/actor_call.go +++ b/sdk/sys/actor_call.go @@ -3,59 +3,65 @@ package sys -/// Resolves the ID address of an actor. -/// -/// # Errors -/// -/// | Error | Reason | -/// |-------------------|-----------------------------------------------------------| -/// | `NotFound` | target actor doesn't exist | -/// | `IllegalArgument` | if the passed address buffer isn't valid, in memory, etc. | +// / Resolves the ID address of an actor. +// / +// / # Errors +// / +// / | Error | Reason | +// / |-------------------|-----------------------------------------------------------| +// / | `NotFound` | target actor doesn't exist | +// / | `IllegalArgument` | if the passed address buffer isn't valid, in memory, etc. | +// //go:wasm-module actor //export resolve_address func actorResolveAddress(ret uintptr, addr_off uintptr, addr_len uint32) uint32 -/// Gets the CodeCID of an actor by address. -/// -/// Returns the -/// -/// # Errors -/// -/// | Error | Reason | -/// |-------------------|-----------------------------------------------------------| -/// | `NotFound` | target actor doesn't exist | -/// | `IllegalArgument` | if the passed address buffer isn't valid, in memory, etc. | +// / Gets the CodeCID of an actor by address. +// / +// / Returns the +// / +// / # Errors +// / +// / | Error | Reason | +// / |-------------------|-----------------------------------------------------------| +// / | `NotFound` | target actor doesn't exist | +// / | `IllegalArgument` | if the passed address buffer isn't valid, in memory, etc. | +// //go:wasm-module actor //export get_actor_code_cid func actorGetActorCodeCid(ret uintptr, addr_off uintptr, addr_len uint32, obuf_off uintptr, obuf_len uint32) uint32 -/// Determines whether the specified CodeCID belongs to that of a builtin -/// actor and which. Returns 0 if unrecognized. Can only fail due to -/// internal errors. +// / Determines whether the specified CodeCID belongs to that of a builtin +// / actor and which. Returns 0 if unrecognized. Can only fail due to +// / internal errors. +// //go:wasm-module actor //export resolve_builtin_actor_type func actorResolveBuiltinActorType(ret uintptr, cid_off uintptr) uint32 -/// Returns the CodeCID for the given built-in actor type. Aborts with exit -/// code IllegalArgument if the supplied type is invalid. Returns the -/// length of the written CID written to the output buffer. Can only -/// return a failure due to internal errors. +// / Returns the CodeCID for the given built-in actor type. Aborts with exit +// / code IllegalArgument if the supplied type is invalid. Returns the +// / length of the written CID written to the output buffer. Can only +// / return a failure due to internal errors. +// //go:wasm-module actor //export get_code_cid_for_type func actorGetCodeCidForType(ret uintptr, typ int32, obuf_off uintptr, obuf_len uint32) uint32 -/// Generates a new actor address for an actor deployed -/// by the calling actor. -/// -/// **Privledged:** May only be called by the init actor. +// / Generates a new actor address for an actor deployed +// / by the calling actor. +// / +// / **Privledged:** May only be called by the init actor. +// //go:wasm-module actor //export new_actor_address func actorNewActorAddress(ret uintptr, obuf_off uintptr, obuf_len uint32) uint32 -/// Creates a new actor of the specified type in the state tree, under -/// the provided address. -/// -/// **Privledged:** May only be called by the init actor. +// / Creates a new actor of the specified type in the state tree, under +// / the provided address. +// / +// / **Privledged:** May only be called by the init actor. +// //go:wasm-module actor //export create_actor func actorCreateActor(actor_id uint64, typ_off uintptr) uint32 diff --git a/sdk/sys/context_call.go b/sdk/sys/context_call.go index f21b9f0..702c404 100644 --- a/sdk/sys/context_call.go +++ b/sdk/sys/context_call.go @@ -3,11 +3,12 @@ package sys -/// Returns the details about this invocation. -/// -/// # Errors -/// -/// None +// / Returns the details about this invocation. +// / +// / # Errors +// / +// / None +// //go:wasm-module vm //export context func vmContext(ret uintptr) uint32 diff --git a/sdk/sys/crypto_call.go b/sdk/sys/crypto_call.go index 2488b65..1242986 100644 --- a/sdk/sys/crypto_call.go +++ b/sdk/sys/crypto_call.go @@ -3,124 +3,133 @@ package sys -/// Verifies that a signature is valid for an address and plaintext. -/// -/// Returns 0 on success, or -1 if the signature fails to validate. -/// -/// # Errors -/// -/// | Error | Reason | -/// |-------------------|------------------------------------------------------| -/// | `IllegalArgument` | signature, address, or plaintext buffers are invalid | +// / Verifies that a signature is valid for an address and plaintext. +// / +// / Returns 0 on success, or -1 if the signature fails to validate. +// / +// / # Errors +// / +// / | Error | Reason | +// / |-------------------|------------------------------------------------------| +// / | `IllegalArgument` | signature, address, or plaintext buffers are invalid | +// //go:wasm-module crypto //export verify_signature func cryptoVerifySignature(ret uintptr, sigOff uintptr, sigLen uint32, addrOff uintptr, addrLen uint32, plainTextOff uintptr, plainTextLen uint32) uint32 -/// Hashes input data using blake2b with 256 bit output. -/// -/// The output buffer must be sized to a minimum of 32 bytes. -/// -/// # Errors -/// -/// | Error | Reason | -/// |-------------------|-------------------------------------------------| -/// | `IllegalArgument` | the input buffer does not point to valid memory | +// / Hashes input data using blake2b with 256 bit output. +// / +// / The output buffer must be sized to a minimum of 32 bytes. +// / +// / # Errors +// / +// / | Error | Reason | +// / |-------------------|-------------------------------------------------| +// / | `IllegalArgument` | the input buffer does not point to valid memory | +// //go:wasm-module crypto //export hash_blake2b func cryptoHashBlake2b(ret uintptr, dataOff uintptr, dataLen uint32) uint32 -/// Computes an unsealed sector CID (CommD) from its constituent piece CIDs -/// (CommPs) and sizes. -/// -/// Writes the CID in the provided output buffer, and returns the length of -/// the written CID. -/// -/// # Errors -/// -/// | Error | Reason | -/// |-------------------|--------------------------| -/// | `IllegalArgument` | an argument is malformed | +// / Computes an unsealed sector CID (CommD) from its constituent piece CIDs +// / (CommPs) and sizes. +// / +// / Writes the CID in the provided output buffer, and returns the length of +// / the written CID. +// / +// / # Errors +// / +// / | Error | Reason | +// / |-------------------|--------------------------| +// / | `IllegalArgument` | an argument is malformed | +// //go:wasm-module crypto //export compute_unsealed_sector_cid func cryptoComputeUnsealedSectorCid(ret uintptr, proofType int64, piecesOff uintptr, pieceLen uint32, cidPtr uintptr, cidLen uint32) uint32 -/// Verifies a sector seal proof. -/// -/// Returns 0 to indicate that the proof was valid, -1 otherwise. -/// -/// # Errors -/// -/// | Error | Reason | -/// |-------------------|--------------------------| -/// | `IllegalArgument` | an argument is malformed | +// / Verifies a sector seal proof. +// / +// / Returns 0 to indicate that the proof was valid, -1 otherwise. +// / +// / # Errors +// / +// / | Error | Reason | +// / |-------------------|--------------------------| +// / | `IllegalArgument` | an argument is malformed | +// //go:wasm-module crypto //export verify_seal func cryptoVerifySeal(ret uintptr, infoOff uintptr, infoLen uint32) uint32 -/// Verifies a window proof of spacetime. -/// -/// Returns 0 to indicate that the proof was valid, -1 otherwise. -/// -/// # Errors -/// -/// | Error | Reason | -/// |-------------------|--------------------------| -/// | `IllegalArgument` | an argument is malformed | +// / Verifies a window proof of spacetime. +// / +// / Returns 0 to indicate that the proof was valid, -1 otherwise. +// / +// / # Errors +// / +// / | Error | Reason | +// / |-------------------|--------------------------| +// / | `IllegalArgument` | an argument is malformed | +// //go:wasm-module crypto //export verify_post func cryptoVerifyPost(ret uintptr, infoOff uintptr, infoLen uint32) uint32 -/// Verifies that two block headers provide proof of a consensus fault. -/// -/// Returns a 0 status if a consensus fault was recognized, along with the -/// BlockId containing the fault details. Otherwise, a -1 status is returned, -/// and the second result parameter must be ignored. -/// -/// # Errors -/// -/// | Error | Reason | -/// |-------------------|---------------------------------------| -/// | `LimitExceeded` | exceeded lookback limit finding block | -/// | `IllegalArgument` | an argument is malformed | +// / Verifies that two block headers provide proof of a consensus fault. +// / +// / Returns a 0 status if a consensus fault was recognized, along with the +// / BlockId containing the fault details. Otherwise, a -1 status is returned, +// / and the second result parameter must be ignored. +// / +// / # Errors +// / +// / | Error | Reason | +// / |-------------------|---------------------------------------| +// / | `LimitExceeded` | exceeded lookback limit finding block | +// / | `IllegalArgument` | an argument is malformed | +// //go:wasm-module crypto //export verify_consensus_fault func cryptoVerifyConsensusFault(ret uintptr, h1Off uintptr, h1Len uint32, h2Off uintptr, h2Len uint32, extraOff uintptr, extraLen uint32) uint32 -/// Verifies an aggregated batch of sector seal proofs. -/// -/// Returns 0 to indicate that the proof was valid, -1 otherwise. -/// -/// # Errors -/// -/// | Error | Reason | -/// |-------------------|--------------------------------| -/// | `LimitExceeded` | exceeds seal aggregation limit | -/// | `IllegalArgument` | an argument is malformed | +// / Verifies an aggregated batch of sector seal proofs. +// / +// / Returns 0 to indicate that the proof was valid, -1 otherwise. +// / +// / # Errors +// / +// / | Error | Reason | +// / |-------------------|--------------------------------| +// / | `LimitExceeded` | exceeds seal aggregation limit | +// / | `IllegalArgument` | an argument is malformed | +// //go:wasm-module crypto //export verify_aggregate_seals func cryptoVerifyAggregateSeals(ret uintptr, aggOff uintptr, aggLen uint32) uint32 -/// Verifies a replica update proof. -/// -/// Returns 0 to indicate that the proof was valid, -1 otherwise. -/// -/// # Errors -/// -/// | Error | Reason | -/// |-------------------|-------------------------------| -/// | `LimitExceeded` | exceeds replica update limit | -/// | `IllegalArgument` | an argument is malformed | +// / Verifies a replica update proof. +// / +// / Returns 0 to indicate that the proof was valid, -1 otherwise. +// / +// / # Errors +// / +// / | Error | Reason | +// / |-------------------|-------------------------------| +// / | `LimitExceeded` | exceeds replica update limit | +// / | `IllegalArgument` | an argument is malformed | +// //go:wasm-module crypto //export verify_replica_update func cryptoVerifyReplicaUpdate(ret uintptr, repOff uintptr, repLen uint32) uint32 -/// Verifies an aggregated batch of sector seal proofs. -/// -/// # Errors -/// -/// | Error | Reason | -/// |-------------------|--------------------------| -/// | `IllegalArgument` | an argument is malformed | +// / Verifies an aggregated batch of sector seal proofs. +// / +// / # Errors +// / +// / | Error | Reason | +// / |-------------------|--------------------------| +// / | `IllegalArgument` | an argument is malformed | +// //go:wasm-module crypto //export batch_verify_seals func cryptoBatchVerifySeals(batchOff uintptr, batLen uint32, resultOff uintptr) uint32 diff --git a/sdk/sys/debug_call.go b/sdk/sys/debug_call.go index 542e5af..fab7aba 100644 --- a/sdk/sys/debug_call.go +++ b/sdk/sys/debug_call.go @@ -3,13 +3,15 @@ package sys -/// Returns if we're in debug mode. A zero or positive return value means -/// yes, a negative return value means no. +// / Returns if we're in debug mode. A zero or positive return value means +// / yes, a negative return value means no. +// //go:wasm-module debug //export enabled func debugEnabled(ret uintptr) uint32 -/// Logs a message on the node. +// / Logs a message on the node. +// //go:wasm-module debug //export log func debugLog(message uintptr, message_len uint32) uint32 diff --git a/sdk/sys/gas_call.go b/sdk/sys/gas_call.go index f039637..4715240 100644 --- a/sdk/sys/gas_call.go +++ b/sdk/sys/gas_call.go @@ -6,19 +6,20 @@ package sys // TODO: name for debugging & tracing? // We could also _not_ feed that through to the outside? -/// Charge gas. -/// -/// # Arguments -/// -/// - `name_off` and `name_len` specify the location and length of the "name" of the gas charge, -/// for debugging. -/// - `amount` is the amount of gas to charge. -/// -/// # Errors -/// -/// | Error | Reason | -/// |---------------------|----------------------| -/// | [`IllegalArgument`] | invalid name buffer. | +// / Charge gas. +// / +// / # Arguments +// / +// / - `name_off` and `name_len` specify the location and length of the "name" of the gas charge, +// / for debugging. +// / - `amount` is the amount of gas to charge. +// / +// / # Errors +// / +// / | Error | Reason | +// / |---------------------|----------------------| +// / | [`IllegalArgument`] | invalid name buffer. | +// //go:wasm-module gas //export charge func gasCharge(name_off uintptr, name_len uint32, amount uint64) uint32 diff --git a/sdk/sys/ipld_call.go b/sdk/sys/ipld_call.go index 548045b..36e800b 100644 --- a/sdk/sys/ipld_call.go +++ b/sdk/sys/ipld_call.go @@ -3,113 +3,118 @@ package sys -/// Opens a block from the "reachable" set, returning an ID for the block, its codec, and its -/// size in bytes. -/// -/// - The reachable set is initialized to the root. -/// - The reachable set is extended to include the direct children of loaded blocks until the -/// end of the invocation. -/// -/// # Arguments -/// -/// - `cid` the location of the input CID (in wasm memory). -/// -/// # Errors -/// -/// | Error | Reason | -/// |---------------------|---------------------------------------------| -/// | [`NotFound`] | the target block isn't in the reachable set | -/// | [`IllegalArgument`] | there's something wrong with the CID | +// / Opens a block from the "reachable" set, returning an ID for the block, its codec, and its +// / size in bytes. +// / +// / - The reachable set is initialized to the root. +// / - The reachable set is extended to include the direct children of loaded blocks until the +// / end of the invocation. +// / +// / # Arguments +// / +// / - `cid` the location of the input CID (in wasm memory). +// / +// / # Errors +// / +// / | Error | Reason | +// / |---------------------|---------------------------------------------| +// / | [`NotFound`] | the target block isn't in the reachable set | +// / | [`IllegalArgument`] | there's something wrong with the CID | +// //go:wasm-module ipld //export block_open func ipldOpen(ret uintptr, cid uintptr) uint32 -/// Creates a new block, returning the block's ID. The block's children must be in the reachable -/// set. The new block isn't added to the reachable set until the CID is computed. -/// -/// # Arguments -/// -/// - `codec` is the codec of the block. -/// - `data` and `len` specify the location and length of the block data. -/// -/// # Errors -/// -/// | Error | Reason | -/// |---------------------|---------------------------------------------------------| -/// | [`LimitExceeded`] | the block is too big | -/// | [`NotFound`] | one of the blocks's children isn't in the reachable set | -/// | [`IllegalCodec`] | the passed codec isn't supported | -/// | [`Serialization`] | the passed block doesn't match the passed codec | -/// | [`IllegalArgument`] | the block isn't in memory, etc. | +// / Creates a new block, returning the block's ID. The block's children must be in the reachable +// / set. The new block isn't added to the reachable set until the CID is computed. +// / +// / # Arguments +// / +// / - `codec` is the codec of the block. +// / - `data` and `len` specify the location and length of the block data. +// / +// / # Errors +// / +// / | Error | Reason | +// / |---------------------|---------------------------------------------------------| +// / | [`LimitExceeded`] | the block is too big | +// / | [`NotFound`] | one of the blocks's children isn't in the reachable set | +// / | [`IllegalCodec`] | the passed codec isn't supported | +// / | [`Serialization`] | the passed block doesn't match the passed codec | +// / | [`IllegalArgument`] | the block isn't in memory, etc. | +// //go:wasm-module ipld //export block_create func ipldCreate(ret uintptr, codec uint64, dataOff uintptr, len uint32) uint32 -/// Reads the block identified by `id` into `obuf`, starting at `offset`, reading _at most_ -/// `max_len` bytes. -/// -/// Returns the difference between the length of the block and `offset + max_len`. This can be -/// used to find the end of the block relative to the buffer the block is being read into: -/// -/// - A zero return value means that the block was read into the output buffer exactly. -/// - A positive return value means that that many more bytes need to be read. -/// - A negative return value means that the buffer should be truncated by the return value. -/// -/// # Arguments -/// -/// - `id` is ID of the block to read. -/// - `offset` is the offset in the block to start reading. -/// - `obuf` is the output buffer (in wasm memory) where the FVM will write the block data. -/// - `max_len` is the maximum amount of block data to read. -/// -/// Passing a length/offset that exceed the length of the block will not result in an error, but -/// will result in no data being read and a negative return value indicating where the block -/// actually ended (relative to `offset + max_len`). -/// -/// # Errors -/// -/// | Error | Reason | -/// |---------------------|---------------------------------------------------| -/// | [`InvalidHandle`] | if the handle isn't known. | -/// | [`IllegalArgument`] | if the passed buffer isn't valid, in memory, etc. | +// / Reads the block identified by `id` into `obuf`, starting at `offset`, reading _at most_ +// / `max_len` bytes. +// / +// / Returns the difference between the length of the block and `offset + max_len`. This can be +// / used to find the end of the block relative to the buffer the block is being read into: +// / +// / - A zero return value means that the block was read into the output buffer exactly. +// / - A positive return value means that that many more bytes need to be read. +// / - A negative return value means that the buffer should be truncated by the return value. +// / +// / # Arguments +// / +// / - `id` is ID of the block to read. +// / - `offset` is the offset in the block to start reading. +// / - `obuf` is the output buffer (in wasm memory) where the FVM will write the block data. +// / - `max_len` is the maximum amount of block data to read. +// / +// / Passing a length/offset that exceed the length of the block will not result in an error, but +// / will result in no data being read and a negative return value indicating where the block +// / actually ended (relative to `offset + max_len`). +// / +// / # Errors +// / +// / | Error | Reason | +// / |---------------------|---------------------------------------------------| +// / | [`InvalidHandle`] | if the handle isn't known. | +// / | [`IllegalArgument`] | if the passed buffer isn't valid, in memory, etc. | +// //go:wasm-module ipld //export block_read func ipldRead(ret uintptr, id uint32, offset uint32, obuf uintptr, max_len uint32) uint32 -/// Returns the codec and size of the specified block. -/// -/// # Errors -/// -/// | Error | Reason | -/// |-------------------|----------------------------| -/// | [`InvalidHandle`] | if the handle isn't known. | +// / Returns the codec and size of the specified block. +// / +// / # Errors +// / +// / | Error | Reason | +// / |-------------------|----------------------------| +// / | [`InvalidHandle`] | if the handle isn't known. | +// //go:wasm-module ipld //export block_stat func ipldStat(ret uintptr, id uint32) uint32 -/// Computes the given block's CID, writing the resulting CID into `cid`. -/// -/// The returned CID is added to the reachable set. -/// -/// # Arguments -/// -/// - `id` is ID of the block to link. -/// - `hash_fun` is the multicodec of the hash function to use. -/// - `hash_len` is the desired length of the hash digest. -/// - `cid` is the output buffer (in wasm memory) where the FVM will write the resulting cid. -/// - `cid_max_length` is the length of the output CID buffer. -/// -/// # Returns -/// -/// The length of the CID. -/// -/// # Errors -/// -/// | Error | Reason | -/// |---------------------|---------------------------------------------------| -/// | [`InvalidHandle`] | if the handle isn't known. | -/// | [`IllegalCid`] | hash code and/or hash length aren't supported. | -/// | [`IllegalArgument`] | if the passed buffer isn't valid, in memory, etc. | +// / Computes the given block's CID, writing the resulting CID into `cid`. +// / +// / The returned CID is added to the reachable set. +// / +// / # Arguments +// / +// / - `id` is ID of the block to link. +// / - `hash_fun` is the multicodec of the hash function to use. +// / - `hash_len` is the desired length of the hash digest. +// / - `cid` is the output buffer (in wasm memory) where the FVM will write the resulting cid. +// / - `cid_max_length` is the length of the output CID buffer. +// / +// / # Returns +// / +// / The length of the CID. +// / +// / # Errors +// / +// / | Error | Reason | +// / |---------------------|---------------------------------------------------| +// / | [`InvalidHandle`] | if the handle isn't known. | +// / | [`IllegalCid`] | hash code and/or hash length aren't supported. | +// / | [`IllegalArgument`] | if the passed buffer isn't valid, in memory, etc. | +// //go:wasm-module ipld //export block_link func ipldLink(ret uintptr, id uint32, hash_fun uint64, hash_len uint32, cid uintptr, cid_max_len uint32) uint32 diff --git a/sdk/sys/network_call.go b/sdk/sys/network_call.go index a87d26c..51a530d 100644 --- a/sdk/sys/network_call.go +++ b/sdk/sys/network_call.go @@ -3,20 +3,22 @@ package sys -/// Gets the base fee for the current epoch. -/// -/// # Errors -/// -/// None +// / Gets the base fee for the current epoch. +// / +// / # Errors +// / +// / None +// //go:wasm-module network //export base_fee func networkBaseFee(ret uintptr) uint32 -/// Gets the circulating supply. -/// -/// # Errors -/// -/// None +// / Gets the circulating supply. +// / +// / # Errors +// / +// / None +// //go:wasm-module network //export total_fil_circ_supply func networkTotalFilCircSupply(ret uintptr) uint32 diff --git a/sdk/sys/rand_call.go b/sdk/sys/rand_call.go index 88bed3a..62254fb 100644 --- a/sdk/sys/rand_call.go +++ b/sdk/sys/rand_call.go @@ -3,42 +3,44 @@ package sys -/// Gets 32 bytes of randomness from the ticket chain. -/// -/// # Arguments -/// -/// - `tag` is the "domain separation tag" for distinguishing between different categories of -/// randomness. Think of it like extra, structured entropy. -/// - `epoch` is the epoch to pull the randomness from. -/// - `entropy_off` and `entropy_len` specify the location and length of the entropy buffer that -/// will be mixed into the system randomness. -/// -/// # Errors -/// -/// | Error | Reason | -/// |---------------------|-------------------------| -/// | [`LimitExceeded`] | lookback exceeds limit. | -/// | [`IllegalArgument`] | invalid buffer, etc. | +// / Gets 32 bytes of randomness from the ticket chain. +// / +// / # Arguments +// / +// / - `tag` is the "domain separation tag" for distinguishing between different categories of +// / randomness. Think of it like extra, structured entropy. +// / - `epoch` is the epoch to pull the randomness from. +// / - `entropy_off` and `entropy_len` specify the location and length of the entropy buffer that +// / will be mixed into the system randomness. +// / +// / # Errors +// / +// / | Error | Reason | +// / |---------------------|-------------------------| +// / | [`LimitExceeded`] | lookback exceeds limit. | +// / | [`IllegalArgument`] | invalid buffer, etc. | +// //go:wasm-module rand //export get_chain_randomness func getChainRandomness(ret uintptr, tag int64, epoch int64, entropy_off uintptr, entropy_len uint32) uint32 -/// Gets 32 bytes of randomness from the beacon system (currently Drand). -/// -/// # Arguments -/// -/// - `tag` is the "domain separation tag" for distinguishing between different categories of -/// randomness. Think of it like extra, structured entropy. -/// - `epoch` is the epoch to pull the randomness from. -/// - `entropy_off` and `entropy_len` specify the location and length of the entropy buffer that -/// will be mixed into the system randomness. -/// -/// # Errors -/// -/// | Error | Reason | -/// |---------------------|-------------------------| -/// | [`LimitExceeded`] | lookback exceeds limit. | -/// | [`IllegalArgument`] | invalid buffer, etc. | +// / Gets 32 bytes of randomness from the beacon system (currently Drand). +// / +// / # Arguments +// / +// / - `tag` is the "domain separation tag" for distinguishing between different categories of +// / randomness. Think of it like extra, structured entropy. +// / - `epoch` is the epoch to pull the randomness from. +// / - `entropy_off` and `entropy_len` specify the location and length of the entropy buffer that +// / will be mixed into the system randomness. +// / +// / # Errors +// / +// / | Error | Reason | +// / |---------------------|-------------------------| +// / | [`LimitExceeded`] | lookback exceeds limit. | +// / | [`IllegalArgument`] | invalid buffer, etc. | +// //go:wasm-module rand //export get_beacon_randomness func getBeaconRandomness(ret uintptr, tag int64, epoch int64, entropy_off uintptr, entropy_len uint32) uint32 diff --git a/sdk/sys/send_call.go b/sdk/sys/send_call.go index 668835b..b01dc54 100644 --- a/sdk/sys/send_call.go +++ b/sdk/sys/send_call.go @@ -3,34 +3,35 @@ package sys -/// Sends a message to another actor, and returns the exit code and block ID of the return -/// result. -/// -/// # Arguments -/// -/// - `recipient_off` and `recipient_len` specify the location and length of the recipient's -/// address (in wasm memory). -/// - `method` is the method number to invoke. -/// - `params` is the IPLD block handle of the method parameters. -/// - `value_hi` are the "high" bits of the token value to send (little-endian) in attoFIL. -/// - `value_lo` are the "high" bits of the token value to send (little-endian) in attoFIL. -/// -/// **NOTE**: This syscall will transfer `(value_hi << 64) | (value_lo)` attoFIL to the -/// recipient. -/// -/// # Errors -/// -/// A syscall error in [`send`] means the _caller_ did something wrong. If the _callee_ panics, -/// exceeds some limit, aborts, aborts with an invalid code, etc., the syscall will _succeed_ -/// and the failure will be reflected in the exit code contained in the return value. -/// -/// | Error | Reason | -/// |-----------------------|------------------------------------------------------| -/// | [`NotFound`] | target actor does not exist and cannot be created. | -/// | [`InsufficientFunds`] | tried to send more FIL than available. | -/// | [`InvalidHandle`] | parameters block not found. | -/// | [`LimitExceeded`] | recursion limit reached. | -/// | [`IllegalArgument`] | invalid recipient address buffer. | +// / Sends a message to another actor, and returns the exit code and block ID of the return +// / result. +// / +// / # Arguments +// / +// / - `recipient_off` and `recipient_len` specify the location and length of the recipient's +// / address (in wasm memory). +// / - `method` is the method number to invoke. +// / - `params` is the IPLD block handle of the method parameters. +// / - `value_hi` are the "high" bits of the token value to send (little-endian) in attoFIL. +// / - `value_lo` are the "high" bits of the token value to send (little-endian) in attoFIL. +// / +// / **NOTE**: This syscall will transfer `(value_hi << 64) | (value_lo)` attoFIL to the +// / recipient. +// / +// / # Errors +// / +// / A syscall error in [`send`] means the _caller_ did something wrong. If the _callee_ panics, +// / exceeds some limit, aborts, aborts with an invalid code, etc., the syscall will _succeed_ +// / and the failure will be reflected in the exit code contained in the return value. +// / +// / | Error | Reason | +// / |-----------------------|------------------------------------------------------| +// / | [`NotFound`] | target actor does not exist and cannot be created. | +// / | [`InsufficientFunds`] | tried to send more FIL than available. | +// / | [`InvalidHandle`] | parameters block not found. | +// / | [`LimitExceeded`] | recursion limit reached. | +// / | [`IllegalArgument`] | invalid recipient address buffer. | +// //go:wasm-module send //export send func sysSend(ret uintptr, recipient_off uintptr, recipient_len uint32, method uint64, params uint32, value_hi uint64, value_lo uint64) uint32 diff --git a/sdk/sys/simulated/doc.go b/sdk/sys/simulated/doc.go new file mode 100644 index 0000000..385e0ee --- /dev/null +++ b/sdk/sys/simulated/doc.go @@ -0,0 +1,2 @@ +// Package simulated is simulated of fvm +package simulated diff --git a/sdk/sys/simulated/error.go b/sdk/sys/simulated/error.go index fc62295..0b3ca0d 100644 --- a/sdk/sys/simulated/error.go +++ b/sdk/sys/simulated/error.go @@ -3,10 +3,10 @@ package simulated import "errors" var ( - ErrorIdValid = errors.New("id is valid") - ErrorNotFound = errors.New("key is not found ") - ErrorKeyExists = errors.New("key already exists") - ErrorKeyMatchSucess = errors.New("key match is ok") - ErrorKeyMatchFail = errors.New("key match is fail") + ErrorIDValid = errors.New("id is valid") + ErrorNotFound = errors.New("key is not found ") + ErrorKeyExists = errors.New("key already exists") + ErrorKeyMatchSucess = errors.New("key match is ok") + ErrorKeyMatchFail = errors.New("key match is fail") ErrorKeyTypeException = errors.New("key type is except") ) diff --git a/sdk/sys/simulated/opration.go b/sdk/sys/simulated/opration.go index 1f124f9..59c9f7d 100644 --- a/sdk/sys/simulated/opration.go +++ b/sdk/sys/simulated/opration.go @@ -45,6 +45,7 @@ func (s *Fsm) SelfDestruct(addr address.Address) error { return nil } +// nolint func (s *Fsm) Create(codec uint64, data []byte) (uint32, error) { index := s.blockCreate(codec, data) return uint32(index), nil @@ -112,6 +113,7 @@ func (s *Fsm) CreateActor(actorID abi.ActorID, codeCid cid.Cid) error { return nil } +// nolint func (s *Fsm) Abort(code uint32, msg string) { panic(fmt.Sprintf("%d:%s", code, msg)) } diff --git a/sdk/sys/simulated/options.go b/sdk/sys/simulated/options.go index 8e293d0..f3a8088 100644 --- a/sdk/sys/simulated/options.go +++ b/sdk/sys/simulated/options.go @@ -1,3 +1,4 @@ +//nolint:unparam package simulated import ( @@ -8,11 +9,11 @@ import ( "github.com/ipfs-force-community/go-fvm-sdk/sdk/types" ) -func SetActorAndAddress(actorId uint32, actorState migration.Actor, addr address.Address) { +func SetActorAndAddress(actorID uint32, actorState migration.Actor, addr address.Address) { DefaultFsm.actorMutex.Lock() defer DefaultFsm.actorMutex.Unlock() - DefaultFsm.actorsMap.Store(actorId, actorState) - DefaultFsm.addressMap.Store(addr, actorId) + DefaultFsm.actorsMap.Store(actorID, actorState) + DefaultFsm.addressMap.Store(addr, actorID) } type SendMock struct { @@ -35,12 +36,12 @@ func SetSend(mock ...SendMock) { } -func SetAccount(actorId uint32, addr address.Address, actor migration.Actor) { +func SetAccount(actorID uint32, addr address.Address, actor migration.Actor) { DefaultFsm.actorMutex.Lock() defer DefaultFsm.actorMutex.Unlock() - DefaultFsm.actorsMap.Store(actorId, actor) - DefaultFsm.addressMap.Store(addr, actorId) + DefaultFsm.actorsMap.Store(actorID, actor) + DefaultFsm.addressMap.Store(addr, actorID) } func SetBaseFee(ta abi.TokenAmount) { diff --git a/sdk/sys/simulated/state.go b/sdk/sys/simulated/state.go index c2765e8..f2254bf 100644 --- a/sdk/sys/simulated/state.go +++ b/sdk/sys/simulated/state.go @@ -1,3 +1,4 @@ +//nolint:unparam package simulated import ( @@ -12,6 +13,7 @@ import ( mh "github.com/multiformats/go-multihash" ) +//nolint type IpldOpen struct { codec uint64 id uint32 @@ -94,12 +96,12 @@ func newSate() *Fsm { return &Fsm{blockid: 1, Ipld: sync.Map{}} } -func (s *Fsm) blockLink(blockid uint32, hash_fun uint64, hash_len uint32) (cided cid.Cid, err error) { - block, err := s.getBlock((blockid)) +func (s *Fsm) blockLink(blockid uint32, hashfun uint64, hashlen uint32) (cided cid.Cid, err error) { + block, err := s.getBlock(blockid) if err != nil { return cid.Undef, err } - Mult, _ := mh.Sum(block.data, hash_fun, int(hash_len)) + Mult, _ := mh.Sum(block.data, hashfun, int(hashlen)) cided = cid.NewCidV1(block.codec, Mult) s.putData(cided, block.data) return @@ -110,7 +112,7 @@ func (s *Fsm) blockCreate(codec uint64, data []byte) uint32 { return uint32(len(s.blocks) - 1) } -func (s *Fsm) blockOpen(id cid.Cid) (BlockId uint32, BlockStat BlockStat) { +func (s *Fsm) blockOpen(id cid.Cid) (blockID uint32, blockStat BlockStat) { data, _ := s.getData(id) block := block{data: data, codec: id.Prefix().GetCodec()} @@ -128,13 +130,13 @@ func (s *Fsm) blockRead(id uint32, offset uint32) ([]byte, error) { data := block.data if offset >= uint32(len(data)) { - return nil, ErrorIdValid + return nil, ErrorIDValid } return data[offset:], nil } -func (s *Fsm) blockStat(blockId uint32) (*types.IpldStat, error) { - b, err := s.getBlock(blockId) +func (s *Fsm) blockStat(blockID uint32) (*types.IpldStat, error) { + b, err := s.getBlock(blockID) if err != nil { return nil, ErrorNotFound } @@ -162,16 +164,17 @@ func (s *Fsm) putBlock(block block) uint32 { return uint32(len(s.blocks) - 1) } -func (s *Fsm) getBlock(blockId uint32) (block, error) { +func (s *Fsm) getBlock(blockID uint32) (block, error) { s.blocksMutex.Lock() defer s.blocksMutex.Unlock() - if blockId >= uint32(len(s.blocks)) { + if blockID >= uint32(len(s.blocks)) { return block{}, ErrorNotFound } - return s.blocks[blockId], nil + return s.blocks[blockID], nil } +//nolint func (s *Fsm) putActor(actorID uint64, actor migration.Actor) error { _, err := s.getActorWithActorid(uint32(actorID)) if err == nil { @@ -181,6 +184,7 @@ func (s *Fsm) putActor(actorID uint64, actor migration.Actor) error { return nil } +//nolint func (s *Fsm) getActorWithActorid(actorID uint32) (migration.Actor, error) { actor, ok := s.actorsMap.Load(actorID) if ok { @@ -189,6 +193,7 @@ func (s *Fsm) getActorWithActorid(actorID uint32) (migration.Actor, error) { return migration.Actor{}, ErrorNotFound } +//nolint func (s *Fsm) getActorWithAddress(addr address.Address) (migration.Actor, error) { s.actorMutex.Lock() defer s.actorMutex.Unlock() diff --git a/sdk/sys/simulated/utils.go b/sdk/sys/simulated/utils.go index 61cc2bc..7af2a7e 100644 --- a/sdk/sys/simulated/utils.go +++ b/sdk/sys/simulated/utils.go @@ -1,3 +1,4 @@ +//nolint:unparam package simulated import ( @@ -16,10 +17,6 @@ func blakehash(data []byte) []byte { return blake.Sum(data) } -func makeHashSum(hash_fun uint64, data []byte) []byte { - return blakehash(data) -} - type emptyInterface struct { _ uintptr word unsafe.Pointer @@ -38,12 +35,12 @@ func GetStringPointerAndLen(str string) (uintptr, uint32) { // Generate a hash of length 32 bytes func makeRandomness(dst int64, round int64, entropy []byte) []byte { - dst_byte := [8]byte{} - binary.BigEndian.PutUint64(dst_byte[0:8], abs(dst)) - round_byte := [8]byte{} - binary.BigEndian.PutUint64(round_byte[0:8], abs(round)) - entropy = append(entropy, dst_byte[:]...) - entropy = append(entropy, round_byte[:]...) + dstbyte := [8]byte{} + binary.BigEndian.PutUint64(dstbyte[0:8], abs(dst)) + roundbyte := [8]byte{} + binary.BigEndian.PutUint64(roundbyte[0:8], abs(round)) + entropy = append(entropy, dstbyte[:]...) + entropy = append(entropy, roundbyte[:]...) h := sha256.New() h.Write(entropy) result := h.Sum(nil) diff --git a/sdk/sys/sself_call.go b/sdk/sys/sself_call.go index 4091663..cb0930a 100644 --- a/sdk/sys/sself_call.go +++ b/sdk/sys/sself_call.go @@ -3,52 +3,56 @@ package sys -/// Gets the current root for the calling actor. -/// -/// If the CID doesn't fit in the specified maximum length (and/or the length is 0), this -/// function returns the required size and does not update the cid buffer. -/// -/// # Errors -/// -/// | Error | Reason | -/// |--------------------|----------------------------------------------------| -/// | `IllegalOperation` | actor hasn't set the root yet, or has been deleted | -/// | `IllegalArgument` | if the passed buffer isn't valid, in memory, etc. | +// / Gets the current root for the calling actor. +// / +// / If the CID doesn't fit in the specified maximum length (and/or the length is 0), this +// / function returns the required size and does not update the cid buffer. +// / +// / # Errors +// / +// / | Error | Reason | +// / |--------------------|----------------------------------------------------| +// / | `IllegalOperation` | actor hasn't set the root yet, or has been deleted | +// / | `IllegalArgument` | if the passed buffer isn't valid, in memory, etc. | +// //go:wasm-module self //export root func sselfRoot(ret uintptr, cid uintptr, cidMaxLen uint32) uint32 -/// Sets the root CID for the calling actor. The new root must be in the reachable set. -/// -/// # Errors -/// -/// | Error | Reason | -/// |--------------------|------------------------------------------------| -/// | `IllegalOperation` | actor has been deleted | -/// | `NotFound` | specified root CID is not in the reachable set | +// / Sets the root CID for the calling actor. The new root must be in the reachable set. +// / +// / # Errors +// / +// / | Error | Reason | +// / |--------------------|------------------------------------------------| +// / | `IllegalOperation` | actor has been deleted | +// / | `NotFound` | specified root CID is not in the reachable set | +// //go:wasm-module self //export set_root func sselfSetRoot(cid uintptr) uint32 -/// Gets the current balance for the calling actor. -/// -/// # Errors -/// -/// None. +// / Gets the current balance for the calling actor. +// / +// / # Errors +// / +// / None. +// //go:wasm-module self //export current_balance func selfCurrentBalance(ret uintptr) uint32 -/// Destroys the calling actor, sending its current balance -/// to the supplied address, which cannot be itself. -/// -/// # Errors -/// -/// | Error | Reason | -/// |-------------------|----------------------------------------------------------------| -/// | `NotFound` | beneficiary isn't found | -/// | `Forbidden` | beneficiary is not allowed (usually means beneficiary is self) | -/// | `IllegalArgument` | if the passed address buffer isn't valid, in memory, etc. | +// / Destroys the calling actor, sending its current balance +// / to the supplied address, which cannot be itself. +// / +// / # Errors +// / +// / | Error | Reason | +// / |-------------------|----------------------------------------------------------------| +// / | `NotFound` | beneficiary isn't found | +// / | `Forbidden` | beneficiary is not allowed (usually means beneficiary is self) | +// / | `IllegalArgument` | if the passed address buffer isn't valid, in memory, etc. | +// //go:wasm-module self //export self_destruct func selfDestruct(addrOff uintptr, addrLen uint32) uint32 diff --git a/sdk/types/fvm_token_amount.go b/sdk/types/fvm_token_amount.go index 4d8b236..7c27bc3 100644 --- a/sdk/types/fvm_token_amount.go +++ b/sdk/types/fvm_token_amount.go @@ -1,3 +1,4 @@ +//nolint:param package types import ( @@ -43,10 +44,9 @@ func (u TokenAmount) Equals64(v uint64) bool { // Cmp compares u and v and returns: // -// -1 if u < v -// 0 if u == v -// +1 if u > v -// +// -1 if u < v +// 0 if u == v +// +1 if u > v func (u TokenAmount) Cmp(v TokenAmount) int { if u == v { return 0 @@ -59,10 +59,9 @@ func (u TokenAmount) Cmp(v TokenAmount) int { // Cmp64 compares u and v and returns: // -// -1 if u < v -// 0 if u == v -// +1 if u > v -// +// -1 if u < v +// 0 if u == v +// +1 if u > v func (u TokenAmount) Cmp64(v uint64) int { if u.Hi == 0 && u.Lo == v { return 0 diff --git a/sdk/utils.go b/sdk/utils.go index 978bccd..8564984 100644 --- a/sdk/utils.go +++ b/sdk/utils.go @@ -75,7 +75,7 @@ func LoadStateFromCid(cid cid.Cid, state cbor.Unmarshaler) { // nolint } } -//this code was from https://github.com/modern-go/reflect2/blob/2b33151c9bbc5231aea69b8861c540102b087070/reflect2.go#L238, and unable to use this package directly for now +// this code was from https://github.com/modern-go/reflect2/blob/2b33151c9bbc5231aea69b8861c540102b087070/reflect2.go#L238, and unable to use this package directly for now type eface struct { _ unsafe.Pointer data unsafe.Pointer