types

package
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Dec 11, 2018 License: MIT Imports: 16 Imported by: 24

Documentation

Index

Constants

View Source
const (
	// SpecifierLen is the length in bytes of a Specifier.
	SpecifierLen = 16

	// UnlockHashChecksumSize is the size of the checksum used to verify
	// human-readable addresses. It is not a crypytographically secure
	// checksum, it's merely intended to prevent typos. 6 is chosen because it
	// brings the total size of the address to 38 bytes, leaving 2 bytes for
	// potential version additions in the future.
	UnlockHashChecksumSize = 6
)
View Source
const (
	// BlockHeaderSize is the size, in bytes, of a block header.
	// 32 (ParentID) + 8 (Nonce) + 8 (Timestamp) + 32 (MerkleRoot)
	BlockHeaderSize = 80
)

Variables

View Source
var (
	// BlockFrequency is the desired number of seconds that
	// should elapse, on average, between successive Blocks.
	BlockFrequency BlockHeight
	// BlockSizeLimit is the maximum size of a binary-encoded Block
	// that is permitted by the consensus rules.
	BlockSizeLimit = uint64(2e6)
	// DevFundDenom is the denominator of the block subsidy that goes
	// to support development of the network instead of the miners
	DevFundDenom = NewCurrency64(10)
	// DevFundUnlockHash is the unlock hash for the dev fund subsidy
	DevFundUnlockHash = UnlockHash{122, 187, 109, 95, 232, 79, 59, 94, 168, 154, 242, 9, 73, 45, 6, 21, 151, 78, 195, 98, 197, 65, 115, 155, 229, 181, 208, 12, 31, 116, 69, 196}

	// EndOfTime is value to be used when a date in the future is needed for
	// validation
	EndOfTime = time.Unix(0, math.MaxInt64)

	// ExtremeFutureThreshold is a temporal limit beyond which Blocks are
	// discarded by the consensus rules. When incoming Blocks are processed, their
	// Timestamp is allowed to exceed the processor's current time by a small amount.
	// But if the Timestamp is further into the future than ExtremeFutureThreshold,
	// the Block is immediately discarded.
	ExtremeFutureThreshold Timestamp
	// FutureThreshold is a temporal limit beyond which Blocks are
	// discarded by the consensus rules. When incoming Blocks are processed, their
	// Timestamp is allowed to exceed the processor's current time by no more than
	// FutureThreshold. If the excess duration is larger than FutureThreshold, but
	// smaller than ExtremeFutureThreshold, the Block may be held in memory until
	// the Block's Timestamp exceeds the current time by less than FutureThreshold.
	FutureThreshold Timestamp
	// GenesisAllocation is the output creating all the initial coins allocated
	// in the genesis block
	GenesisAllocation []SiacoinOutput
	// GenesisAirdropAllocation is the output creating the initial coins allocated
	// for the airdrop at network launch
	GenesisAirdropAllocation []SiacoinOutput
	// GenesisDeveloperAllocation is the output creating the initial coins allocated
	// for the developer airdrop at network launch
	GenesisDeveloperAllocation []SiacoinOutput
	// GenesisContributorAllocation is the output creating the initial coins allocated
	// for the developer airdrop at network launch
	GenesisContributorAllocation []SiacoinOutput
	// GenesisPoolAllocation is the output creating the initial coins allocated
	// for the developer airdrop at network launch
	GenesisPoolAllocation []SiacoinOutput
	// GenesisBlock is the first block of the block chain
	GenesisBlock Block

	// GenesisID is used in many places. Calculating it once saves lots of
	// redundant computation.
	GenesisID BlockID

	// GenesisTimestamp is the timestamp when genesis block was mined
	GenesisTimestamp Timestamp
	// FirstCoinbase is the coinbase reward of the Genesis block.
	FirstCoinbase = uint64(24e8)
	// SecondCoinbase is the coinbase reward of the 2nd block.
	SecondCoinbase = uint64(6e8)
	// InitialCoinbase is the coinbase reward of the first block following the
	// initial 2 blocks.
	InitialCoinbase = uint64(60e3)
	// AirdropValue is the total amount of coins generated in the genesis block
	// for the airdrop.
	AirdropValue = NewCurrency64(35373763032).Mul(SiacoinPrecision).Div(NewCurrency64(10))
	// SingleDeveloperAirdropValue is the amount of coins generated in the genesis
	// block for each developer's airdrop
	SingleDeveloperAirdropValue = NewCurrency64(54e6).Mul(SiacoinPrecision)
	// NumDevelopers is the number of developers who split the DeveloperAirdrop
	NumDevelopers = uint64(10)
	// DeveloperAirdropValue is the total amount of coins generated in the genesis
	// block for the developers airdrops
	DeveloperAirdropValue = SingleDeveloperAirdropValue.Mul(NewCurrency64(NumDevelopers))
	// SingleContributorAirdropValue is the amount of coins generated in the genesis
	// block for each contributor's airdrop
	SingleContributorAirdropValue = NewCurrency64(10e6).Mul(SiacoinPrecision)
	// NumContributors is the number of contributors who split the ContributorAirdrop
	NumContributors = uint64(6)
	// ContributorAirdropValue is the total amount of coins generated in the genesis
	// block for the contributor airdrop
	ContributorAirdropValue = SingleContributorAirdropValue.Mul(NewCurrency64(NumContributors))
	// SinglePoolAirdropValue is the amount of coins generated in the genesis
	// block for each pool's airdrop
	SinglePoolAirdropValue = NewCurrency64(2 * InitialCoinbase).Mul(SiacoinPrecision)
	// NumPools is the number of developers who split the DeveloperAirdrop
	NumPools = uint64(7)
	// PoolAirdropValue is the total amount of coins generated in the genesis
	// block for the pool airdrop
	PoolAirdropValue = SinglePoolAirdropValue.Mul(NewCurrency64(NumPools))
	// MaturityDelay specifies the number of blocks that a maturity-required output
	// is required to be on hold before it can be spent on the blockchain.
	// Outputs are maturity-required if they are highly likely to be altered or
	// invalidated in the event of a small reorg. One example is the block reward,
	// as a small reorg may invalidate the block reward. File contract payouts also
	// are subject to a maturity delay.
	MaturityDelay BlockHeight
	// MaxTargetAdjustmentDown restrict how much the block difficulty is allowed to
	// change in a single step, which is important to limit the effect of difficulty
	// raising and lowering attacks.
	MaxTargetAdjustmentDown *big.Rat
	// MaxTargetAdjustmentUp restrict how much the block difficulty is allowed to
	// change in a single step, which is important to limit the effect of difficulty
	// raising and lowering attacks.
	MaxTargetAdjustmentUp *big.Rat
	// MedianTimestampWindow tells us how many blocks to look back when calculating
	// the median timestamp over the previous n blocks. The timestamp of a block is
	// not allowed to be less than or equal to the median timestamp of the previous n
	// blocks, where for Sia this number is typically 11.
	MedianTimestampWindow = uint64(11)
	// MinimumCoinbase is the minimum coinbase reward for a block.
	// The coinbase decreases in each block after the Genesis block,
	// but it will not decrease past MinimumCoinbase.
	MinimumCoinbase uint64

	// OakDecayDenom is the denominator for how much the total timestamp is decayed
	// each step.
	OakDecayDenom int64
	// OakDecayNum is the numerator for how much the total timestamp is decayed each
	// step.
	OakDecayNum int64
	// OakTxnSizeLimit is the maximum size allowed for a transaction.
	OakTxnSizeLimit = uint64(64e3) // 64 KB
	// OakMaxBlockShift is the maximum number of seconds that the oak algorithm will shift
	// the difficulty.
	OakMaxBlockShift int64
	// OakMaxDrop is the drop is the maximum amount that the difficulty will drop each block.
	OakMaxDrop *big.Rat
	// OakMaxRise is the maximum amount that the difficulty will rise each block.
	OakMaxRise *big.Rat

	// RootDepth is the cumulative target of all blocks. The root depth is essentially
	// the maximum possible target, there have been no blocks yet, so there is no
	// cumulated difficulty yet.
	RootDepth = Target{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}
	// RootTarget is the target for the genesis block - basically how much work needs
	// to be done in order to mine the first block. The difficulty adjustment algorithm
	// takes over from there.
	RootTarget Target
	// SiacoinPrecision is the number of base units in a siacoin. The Sia network has a very
	// large number of base units. We call 10^24 of these a siacoin.
	//
	// The base unit for Bitcoin is called a satoshi. We call 10^8 satoshis a bitcoin,
	// even though the code itself only ever works with satoshis.
	SiacoinPrecision = NewCurrency(new(big.Int).Exp(big.NewInt(10), big.NewInt(24), nil))
	// TargetWindow is the number of blocks to look backwards when determining how much
	// time has passed vs. how many blocks have been created. It's only used in the old,
	// broken difficulty adjustment algorithm.
	TargetWindow BlockHeight
)
View Source
var (
	// ErrNegativeCurrency is the error that is returned if performing an
	// operation results in a negative currency.
	ErrNegativeCurrency = errors.New("negative currency not allowed")

	// ErrUint64Overflow is the error that is returned if converting to a
	// unit64 would cause an overflow.
	ErrUint64Overflow = errors.New("cannot return the uint64 of this currency - result is an overflow")

	// ZeroCurrency defines a currency of value zero.
	ZeroCurrency = NewCurrency64(0)
)
View Source
var (
	// ErrEntropyKey is the error when a transaction tries to sign an entropy
	// public key
	ErrEntropyKey = errors.New("transaction tries to sign an entropy public key")
	// ErrFrivolousSignature is the error when a transaction contains a frivolous
	// signature
	ErrFrivolousSignature = errors.New("transaction contains a frivolous signature")
	// ErrInvalidPubKeyIndex is the error when a transaction contains a signature
	// that points to a nonexistent public key
	ErrInvalidPubKeyIndex = errors.New("transaction contains a signature that points to a nonexistent public key")
	// ErrInvalidUnlockHashChecksum is the error when the provided unlock hash has
	// an invalid checksum
	ErrInvalidUnlockHashChecksum = errors.New("provided unlock hash has an invalid checksum")
	// ErrMissingSignatures is the error when a transaction has inputs with missing
	// signatures
	ErrMissingSignatures = errors.New("transaction has inputs with missing signatures")
	// ErrPrematureSignature is the error when the timelock on signature has not
	// expired
	ErrPrematureSignature = errors.New("timelock on signature has not expired")
	// ErrPublicKeyOveruse is the error when public key was used multiple times while
	// signing transaction
	ErrPublicKeyOveruse = errors.New("public key was used multiple times while signing transaction")
	// ErrSortedUniqueViolation is the error when a sorted unique violation occurs
	ErrSortedUniqueViolation = errors.New("sorted unique violation")
	// ErrUnlockHashWrongLen is the error when a marshalled unlock hash is the wrong
	// length
	ErrUnlockHashWrongLen = errors.New("marshalled unlock hash is the wrong length")
	// ErrWholeTransactionViolation is the error when there's a covered fields violation
	ErrWholeTransactionViolation = errors.New("covered fields violation")

	// FullCoveredFields is a covered fileds object where the
	// 'WholeTransaction' field has been set to true. The primary purpose of
	// this variable is syntactic sugar.
	FullCoveredFields = CoveredFields{WholeTransaction: true}

	// SignatureEd25519 is a specifier for Ed22519
	SignatureEd25519 = Specifier{'e', 'd', '2', '5', '5', '1', '9'}
	// SignatureEntropy is a specifier for entropy
	SignatureEntropy = Specifier{'e', 'n', 't', 'r', 'o', 'p', 'y'}
)
View Source
var (
	ErrTransactionIDWrongLen = errors.New("input has wrong length to be an encoded transaction id")

	SpecifierClaimOutput          = Specifier{'c', 'l', 'a', 'i', 'm', ' ', 'o', 'u', 't', 'p', 'u', 't'}
	SpecifierFileContract         = Specifier{'f', 'i', 'l', 'e', ' ', 'c', 'o', 'n', 't', 'r', 'a', 'c', 't'}
	SpecifierFileContractRevision = Specifier{'f', 'i', 'l', 'e', ' ', 'c', 'o', 'n', 't', 'r', 'a', 'c', 't', ' ', 'r', 'e'}
	SpecifierMinerFee             = Specifier{'m', 'i', 'n', 'e', 'r', ' ', 'f', 'e', 'e'}
	SpecifierMinerPayout          = Specifier{'m', 'i', 'n', 'e', 'r', ' ', 'p', 'a', 'y', 'o', 'u', 't'}
	SpecifierSiacoinInput         = Specifier{'s', 'p', 'a', 'c', 'e', 'c', 'a', 's', 'h', ' ', 'i', 'n', 'p', 'u', 't'}
	SpecifierSiacoinOutput        = Specifier{'s', 'p', 'a', 'c', 'e', 'c', 'a', 's', 'h', ' ', 'o', 'u', 't', 'p', 'u', 't'}
	SpecifierStorageProof         = Specifier{'s', 't', 'o', 'r', 'a', 'g', 'e', ' ', 'p', 'r', 'o', 'o', 'f'}
	SpecifierStorageProofOutput   = Specifier{'s', 't', 'o', 'r', 'a', 'g', 'e', ' ', 'p', 'r', 'o', 'o', 'f'}
)

These Specifiers are used internally when calculating a type's ID. See Specifier for more details.

View Source
var (
	// ErrDoubleSpend is an error when a transaction uses a parent object
	// twice
	ErrDoubleSpend = errors.New("transaction uses a parent object twice")
	// ErrFileContractOutputSumViolation is an error when a file contract
	// has invalid output sums
	ErrFileContractOutputSumViolation = errors.New("file contract has invalid output sums")
	// ErrFileContractWindowEndViolation is an error when a file contract
	// window must end at least one block after it starts
	ErrFileContractWindowEndViolation = errors.New("file contract window must end at least one block after it starts")
	// ErrFileContractWindowStartViolation is an error when a file contract
	// window must start in the future
	ErrFileContractWindowStartViolation = errors.New("file contract window must start in the future")
	// ErrNonZeroRevision is an error when a new file contract has a
	// nonzero revision number
	ErrNonZeroRevision = errors.New("new file contract has a nonzero revision number")
	// ErrStorageProofWithOutputs is an error when a transaction has both
	// a storage proof and other outputs
	ErrStorageProofWithOutputs = errors.New("transaction has both a storage proof and other outputs")
	// ErrTimelockNotSatisfied is an error when a timelock has not been met
	ErrTimelockNotSatisfied = errors.New("timelock has not been met")
	// ErrTransactionTooLarge is an error when a transaction is too large
	// to fit in a block
	ErrTransactionTooLarge = errors.New("transaction is too large to fit in a block")
	// ErrZeroMinerFee is an error when a transaction has a zero value miner
	// fee
	ErrZeroMinerFee = errors.New("transaction has a zero value miner fee")
	// ErrZeroOutput is an error when a transaction cannot have an output
	// or payout that has zero value
	ErrZeroOutput = errors.New("transaction cannot have an output or payout that has zero value")
	// ErrZeroRevision is an error when a transaction has a file contract
	// revision with RevisionNumber=0
	ErrZeroRevision = errors.New("transaction has a file contract revision with RevisionNumber=0")
)
View Source
var (
	// ErrNegativeTarget is an error when a negative value used when converting
	// to target
	ErrNegativeTarget = errors.New("negative value used when converting to target")
)

Functions

This section is empty.

Types

type Block

type Block struct {
	ParentID     BlockID         `json:"parentid"`
	Nonce        BlockNonce      `json:"nonce"`
	Timestamp    Timestamp       `json:"timestamp"`
	MinerPayouts []SiacoinOutput `json:"minerpayouts"`
	Transactions []Transaction   `json:"transactions"`
}

A Block is a summary of changes to the state that have occurred since the previous block. Blocks reference the ID of the previous block (their "parent"), creating the linked-list commonly known as the blockchain. Their primary function is to bundle together transactions on the network. Blocks are created by "miners," who collect transactions from other nodes, and then try to pick a Nonce that results in a block whose BlockID is below a given Target.

func (Block) CalculateMinerFees

func (b Block) CalculateMinerFees() Currency

CalculateMinerFees calculates the sum of a block's miner transaction fees

func (Block) CalculateSubsidies

func (b Block) CalculateSubsidies(height BlockHeight) (Currency, Currency)

CalculateSubsidies takes a block and a height and determines the block subsidies for miners and the dev fund.

func (Block) Header

func (b Block) Header() BlockHeader

Header returns the header of a block.

func (Block) ID

func (b Block) ID() BlockID

ID returns the ID of a Block, which is calculated by hashing the concatenation of the block's parent's ID, nonce, and the result of the b.MerkleRoot(). It is equivalent to calling block.Header().ID()

func (Block) MarshalSia

func (b Block) MarshalSia(w io.Writer) error

MarshalSia implements the encoding.SiaMarshaler interface.

func (Block) MerkleBranches

func (b Block) MerkleBranches() []string

MerkleBranches returns the merkle branches of a block, as used in stratum mining.

func (Block) MerkleRoot

func (b Block) MerkleRoot() crypto.Hash

MerkleRoot calculates the Merkle root of a Block. The leaves of the Merkle tree are composed of the miner outputs (one leaf per payout), and the transactions (one leaf per transaction).

func (Block) MerkleTree

func (b Block) MerkleTree() *crypto.MerkleTree

MerkleTree return the MerkleTree of the block

func (Block) MinerPayoutID

func (b Block) MinerPayoutID(i uint64) SiacoinOutputID

MinerPayoutID returns the ID of the miner payout at the given index, which is calculated by hashing the concatenation of the BlockID and the payout index.

func (*Block) UnmarshalSia

func (b *Block) UnmarshalSia(r io.Reader) error

UnmarshalSia implements the encoding.SiaUnmarshaler interface.

type BlockHeader

type BlockHeader struct {
	ParentID   BlockID     `json:"parentid"`
	Nonce      BlockNonce  `json:"nonce"`
	Timestamp  Timestamp   `json:"timestamp"`
	MerkleRoot crypto.Hash `json:"merkleroot"`
}

A BlockHeader contains the data that, when hashed, produces the Block's ID.

func (BlockHeader) ID

func (h BlockHeader) ID() BlockID

ID returns the ID of a Block, which is calculated by hashing the header.

type BlockHeight

type BlockHeight uint64

BlockHeight is the number of blocks that exist after the genesis block.

type BlockID

type BlockID crypto.Hash

A BlockID is the hash of a BlockHeader. A BlockID uniquely identifies a Block, and indicates the amount of work performed to mine that Block. The more leading zeros in the BlockID, the more work was performed.

func (*BlockID) LoadString

func (bid *BlockID) LoadString(str string) error

LoadString loads a BlockID from a string

func (BlockID) MarshalJSON

func (bid BlockID) MarshalJSON() ([]byte, error)

MarshalJSON marshales a block id as a hex string.

func (BlockID) String

func (bid BlockID) String() string

String prints the block id in hex.

func (*BlockID) UnmarshalJSON

func (bid *BlockID) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes the json hex string of the block id.

type BlockNonce

type BlockNonce [8]byte

The BlockNonce is a "scratch space" that miners can freely alter to produce a BlockID that satisfies a given Target.

type Clock

type Clock interface {
	Now() Timestamp
}

Clock allows clients to retrieve the current time.

type CoveredFields

type CoveredFields struct {
	WholeTransaction      bool     `json:"wholetransaction"`
	SiacoinInputs         []uint64 `json:"siacoininputs"`
	SiacoinOutputs        []uint64 `json:"siacoinoutputs"`
	FileContracts         []uint64 `json:"filecontracts"`
	FileContractRevisions []uint64 `json:"filecontractrevisions"`
	StorageProofs         []uint64 `json:"storageproofs"`
	MinerFees             []uint64 `json:"minerfees"`
	ArbitraryData         []uint64 `json:"arbitrarydata"`
	TransactionSignatures []uint64 `json:"transactionsignatures"`
}

CoveredFields indicates which fields in a transaction have been covered by the signature. (Note that the signature does not sign the fields themselves, but rather their combined hash; see SigHash.) Each slice corresponds to a slice in the Transaction type, indicating which indices of the slice have been signed. The indices must be valid, i.e. within the bounds of the slice. In addition, they must be sorted and unique.

As a convenience, a signature of the entire transaction can be indicated by the 'WholeTransaction' field. If 'WholeTransaction' == true, all other fields must be empty (except for the Signatures field, since a signature cannot sign itself).

func (CoveredFields) MarshalSia

func (cf CoveredFields) MarshalSia(w io.Writer) error

MarshalSia implements the encoding.SiaMarshaler interface.

func (CoveredFields) MarshalSiaSize

func (cf CoveredFields) MarshalSiaSize() (size int)

MarshalSiaSize returns the encoded size of cf.

func (*CoveredFields) UnmarshalSia

func (cf *CoveredFields) UnmarshalSia(r io.Reader) error

UnmarshalSia implements the encoding.SiaUnmarshaler interface.

type Currency

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

A Currency represents a number of space cash. Internally, a Currency value is unbounded; however, Currency values sent over the wire protocol are subject to a maximum size of 255 bytes (approximately 10^614). Unlike the math/big library, whose methods modify their receiver, all arithmetic Currency methods return a new value. Currency cannot be negative.

func CalculateCoinbase

func CalculateCoinbase(height BlockHeight) Currency

CalculateCoinbase calculates the coinbase for a given height. The coinbase equation is:

coinbase := max(InitialCoinbase - height, MinimumCoinbase) * SiacoinPrecision

func CalculateNumSiacoins

func CalculateNumSiacoins(height BlockHeight) Currency

CalculateNumSiacoins calculates the number of siacoins in circulation at a given height.

func NewCurrency

func NewCurrency(b *big.Int) (c Currency)

NewCurrency creates a Currency value from a big.Int. Undefined behavior occurs if a negative input is used.

func NewCurrency64

func NewCurrency64(x uint64) (c Currency)

NewCurrency64 creates a Currency value from a uint64.

func (Currency) Add

func (x Currency) Add(y Currency) (c Currency)

Add returns a new Currency value c = x + y

func (Currency) Big

func (x Currency) Big() *big.Int

Big returns the value of c as a *big.Int. Importantly, it does not provide access to the c's internal big.Int object, only a copy.

func (Currency) Cmp

func (x Currency) Cmp(y Currency) int

Cmp compares two Currency values. The return value follows the convention of math/big.

func (Currency) Cmp64

func (x Currency) Cmp64(y uint64) int

Cmp64 compares x to a uint64. The return value follows the convention of math/big.

func (Currency) Div

func (x Currency) Div(y Currency) (c Currency)

Div returns a new Currency value c = x / y.

func (Currency) Div64

func (x Currency) Div64(y uint64) (c Currency)

Div64 returns a new Currency value c = x / y.

func (Currency) Equals

func (x Currency) Equals(y Currency) bool

Equals returns true if x and y have the same value.

func (Currency) Equals64

func (x Currency) Equals64(y uint64) bool

Equals64 returns true if x and y have the same value.

func (Currency) HumanString

func (c Currency) HumanString() string

HumanString prints the Currency using human readable units. The unit used will be the largest unit that results in a value greater than 1. The value is rounded to 4 significant digits.

func (Currency) IsZero

func (x Currency) IsZero() bool

IsZero returns true if the value is 0, false otherwise.

func (Currency) MarshalJSON

func (c Currency) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (Currency) MarshalSia

func (c Currency) MarshalSia(w io.Writer) error

MarshalSia implements the encoding.SiaMarshaler interface. It writes the byte-slice representation of the Currency's internal big.Int to w. Note that as the bytes of the big.Int correspond to the absolute value of the integer, there is no way to marshal a negative Currency.

func (Currency) MarshalSiaSize

func (c Currency) MarshalSiaSize() int

MarshalSiaSize returns the encoded size of c.

func (Currency) Mul

func (x Currency) Mul(y Currency) (c Currency)

Mul returns a new Currency value c = x * y.

func (Currency) Mul64

func (x Currency) Mul64(y uint64) (c Currency)

Mul64 returns a new Currency value c = x * y.

func (Currency) MulFloat

func (x Currency) MulFloat(y float64) (c Currency)

MulFloat returns a new Currency value y = c * x, where x is a float64. Behavior is undefined when x is negative.

func (Currency) MulRat

func (x Currency) MulRat(y *big.Rat) (c Currency)

MulRat returns a new Currency value c = x * y, where y is a big.Rat.

func (Currency) RoundDown

func (x Currency) RoundDown(y Currency) (c Currency)

RoundDown returns the largest multiple of y <= x.

func (*Currency) Scan

func (c *Currency) Scan(s fmt.ScanState, ch rune) error

Scan implements the fmt.Scanner interface, allowing Currency values to be scanned from text.

func (Currency) Sqrt

func (x Currency) Sqrt() (c Currency)

Sqrt returns a new Currency value y = sqrt(c). Result is rounded down to the nearest integer.

func (Currency) String

func (c Currency) String() string

String implements the fmt.Stringer interface.

func (Currency) Sub

func (x Currency) Sub(y Currency) (c Currency)

Sub returns a new Currency value c = x - y. Behavior is undefined when x < y.

func (Currency) Uint64

func (x Currency) Uint64() (u uint64, err error)

Uint64 converts a Currency to a uint64. An error is returned because this function is sometimes called on values that can be determined by users - rather than have all user-facing points do input checking, the input checking should happen at the base type. This minimizes the chances of a rogue user causing a build.Critical to be triggered.

func (*Currency) UnmarshalJSON

func (c *Currency) UnmarshalJSON(b []byte) error

UnmarshalJSON implements the json.Unmarshaler interface. An error is returned if a negative number is provided.

func (*Currency) UnmarshalSia

func (c *Currency) UnmarshalSia(r io.Reader) error

UnmarshalSia implements the encoding.SiaUnmarshaler interface.

type ExtraNonce2

type ExtraNonce2 struct {
	Value uint64
	Size  uint
}

ExtraNonce2 is the nonce modified by the miner

func (*ExtraNonce2) Bytes

func (en *ExtraNonce2) Bytes() (b []byte)

Bytes is a bigendian representation of the extranonce2

func (*ExtraNonce2) Increment

func (en *ExtraNonce2) Increment() (err error)

Increment increases the nonce with 1, an error is returned if the resulting is value is bigger than possible given the size

type FileContract

type FileContract struct {
	FileSize           uint64          `json:"filesize"`
	FileMerkleRoot     crypto.Hash     `json:"filemerkleroot"`
	WindowStart        BlockHeight     `json:"windowstart"`
	WindowEnd          BlockHeight     `json:"windowend"`
	Payout             Currency        `json:"payout"`
	ValidProofOutputs  []SiacoinOutput `json:"validproofoutputs"`
	MissedProofOutputs []SiacoinOutput `json:"missedproofoutputs"`
	UnlockHash         UnlockHash      `json:"unlockhash"`
	RevisionNumber     uint64          `json:"revisionnumber"`
}

A FileContract is a public record of a storage agreement between a "host" and a "renter." It mandates that a host must submit a storage proof to the network, proving that they still possess the file they have agreed to store.

The party must submit the storage proof in a block that is between 'WindowStart' and 'WindowEnd'. Upon submitting the proof, the outputs for 'ValidProofOutputs' are created. If the party does not submit a storage proof by 'WindowEnd', then the outputs for 'MissedProofOutputs' are created instead. The sum of 'MissedProofOutputs' and the sum of 'ValidProofOutputs' must equal 'Payout'.

Under normal circumstances, the payout will be funded by both the host and the renter, which gives the host incentive not to lose the file. The 'ValidProofUnlockHash' will typically be spendable by host, and the 'MissedProofUnlockHash' will either by spendable by the renter or by nobody (the ZeroUnlockHash).

A contract can be terminated early by submitting a FileContractTermination whose UnlockConditions hash to 'TerminationHash'.

func (FileContract) MarshalSia

func (fc FileContract) MarshalSia(w io.Writer) error

MarshalSia implements the encoding.SiaMarshaler interface.

func (FileContract) MarshalSiaSize

func (fc FileContract) MarshalSiaSize() (size int)

MarshalSiaSize returns the encoded size of fc.

func (FileContract) OutputUnlockHashes

func (fc FileContract) OutputUnlockHashes() []UnlockHash

OutputUnlockHashes returns a list of all the unlock hashes referenced by this file contract.

func (*FileContract) UnmarshalSia

func (fc *FileContract) UnmarshalSia(r io.Reader) error

UnmarshalSia implements the encoding.SiaUnmarshaler interface.

type FileContractID

type FileContractID crypto.Hash

FileContractID uniquely identifies a file contract

func (*FileContractID) LoadString

func (fcid *FileContractID) LoadString(str string) error

LoadString loads a FileContractID from a string

func (FileContractID) MarshalJSON

func (fcid FileContractID) MarshalJSON() ([]byte, error)

MarshalJSON marshals an id as a hex string.

func (FileContractID) StorageProofOutputID

func (fcid FileContractID) StorageProofOutputID(proofStatus ProofStatus, i uint64) SiacoinOutputID

StorageProofOutputID returns the ID of an output created by a file contract, given the status of the storage proof. The ID is calculating by hashing the concatenation of the StorageProofOutput Specifier, the ID of the file contract that the proof is for, a boolean indicating whether the proof was valid (true) or missed (false), and the index of the output within the file contract.

func (FileContractID) String

func (fcid FileContractID) String() string

String prints the id in hex.

func (*FileContractID) UnmarshalJSON

func (fcid *FileContractID) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes the json hex string of the id.

type FileContractRevision

type FileContractRevision struct {
	ParentID          FileContractID   `json:"parentid"`
	UnlockConditions  UnlockConditions `json:"unlockconditions"`
	NewRevisionNumber uint64           `json:"newrevisionnumber"`

	NewFileSize           uint64          `json:"newfilesize"`
	NewFileMerkleRoot     crypto.Hash     `json:"newfilemerkleroot"`
	NewWindowStart        BlockHeight     `json:"newwindowstart"`
	NewWindowEnd          BlockHeight     `json:"newwindowend"`
	NewValidProofOutputs  []SiacoinOutput `json:"newvalidproofoutputs"`
	NewMissedProofOutputs []SiacoinOutput `json:"newmissedproofoutputs"`
	NewUnlockHash         UnlockHash      `json:"newunlockhash"`
}

A FileContractRevision revises an existing file contract. The ParentID points to the file contract that is being revised. The UnlockConditions are the conditions under which the revision is valid, and must match the UnlockHash of the parent file contract. The Payout of the file contract cannot be changed, but all other fields are allowed to be changed. The sum of the outputs must match the original payout (taking into account the fee for the proof payouts.) A revision number is included. When getting accepted, the revision number of the revision must be higher than any previously seen revision number for that file contract.

FileContractRevisions enable trust-free modifications to existing file contracts.

func (FileContractRevision) MarshalSia

func (fcr FileContractRevision) MarshalSia(w io.Writer) error

MarshalSia implements the encoding.SiaMarshaler interface.

func (FileContractRevision) MarshalSiaSize

func (fcr FileContractRevision) MarshalSiaSize() (size int)

MarshalSiaSize returns the encoded size of fcr.

func (FileContractRevision) OutputUnlockHashes

func (fcr FileContractRevision) OutputUnlockHashes() []UnlockHash

OutputUnlockHashes returns a list of all the unlock hashes referenced by this file contract revision

func (*FileContractRevision) UnmarshalSia

func (fcr *FileContractRevision) UnmarshalSia(r io.Reader) error

UnmarshalSia implements the encoding.SiaUnmarshaler interface.

type GCSFilter

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

GCSFilter wrapper

func NewGCSFilter

func NewGCSFilter(filter *gcs.Filter) GCSFilter

NewGCSFilter wrap filter with NewGCSFilter

func (*GCSFilter) LoadBytes

func (f *GCSFilter) LoadBytes(bytes []byte) error

LoadBytes build filter from bytes

func (GCSFilter) MarshalSia

func (f GCSFilter) MarshalSia(w io.Writer) error

MarshalSia marshal filter to bytes

func (GCSFilter) MatchUnlockHash

func (f GCSFilter) MatchUnlockHash(id []byte, data [][]byte) bool

MatchUnlockHash checks whether an unlockhash in a processed block

func (*GCSFilter) UnmarshalSia

func (f *GCSFilter) UnmarshalSia(r io.Reader) error

UnmarshalSia unmarshal filter from bytes

type OutputID

type OutputID crypto.Hash

OutputID uniquely identifies an output

func (OutputID) MarshalJSON

func (oid OutputID) MarshalJSON() ([]byte, error)

MarshalJSON marshals an id as a hex string.

func (OutputID) String

func (oid OutputID) String() string

String prints the id in hex.

func (*OutputID) UnmarshalJSON

func (oid *OutputID) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes the json hex string of the id.

type ProofStatus

type ProofStatus bool

ProofStatus indicates whether a StorageProof was valid (true) or missed (false).

var (
	// ProofMissed indicates that a StorageProof was missed, which means that
	// no valid proof was submitted within the proof window.
	ProofMissed ProofStatus = false
	// ProofValid indicates that a valid StorageProof was submitted within the
	// proof window.
	ProofValid ProofStatus = true
)

type SiaPublicKey

type SiaPublicKey struct {
	Algorithm Specifier `json:"algorithm"`
	Key       []byte    `json:"key"`
}

A SiaPublicKey is a public key prefixed by a Specifier. The Specifier indicates the algorithm used for signing and verification. Unrecognized algorithms will always verify, which allows new algorithms to be added to the protocol via a soft-fork.

func Ed25519PublicKey

func Ed25519PublicKey(pk crypto.PublicKey) SiaPublicKey

Ed25519PublicKey returns pk as a SiaPublicKey, denoting its algorithm as Ed25519.

func (*SiaPublicKey) LoadString

func (spk *SiaPublicKey) LoadString(s string)

LoadString is the inverse of SiaPublicKey.String().

func (SiaPublicKey) MarshalJSON

func (spk SiaPublicKey) MarshalJSON() ([]byte, error)

MarshalJSON marshals a SiaPublicKey as JSON.

func (SiaPublicKey) MarshalSia

func (spk SiaPublicKey) MarshalSia(w io.Writer) error

MarshalSia implements the encoding.SiaMarshaler interface.

func (*SiaPublicKey) String

func (spk *SiaPublicKey) String() string

String defines how to print a SiaPublicKey - hex is used to keep things compact during logging. The key type prefix and lack of a checksum help to separate it from a sia address.

func (*SiaPublicKey) UnmarshalJSON

func (spk *SiaPublicKey) UnmarshalJSON(b []byte) error

UnmarshalJSON unmarshals a SiaPublicKey as JSON.

func (*SiaPublicKey) UnmarshalSia

func (spk *SiaPublicKey) UnmarshalSia(r io.Reader) error

UnmarshalSia implements the encoding.SiaUnmarshaler interface.

type SiacoinInput

type SiacoinInput struct {
	ParentID         SiacoinOutputID  `json:"parentid"`
	UnlockConditions UnlockConditions `json:"unlockconditions"`
}

A SiacoinInput consumes a SiacoinOutput and adds the siacoins to the set of siacoins that can be spent in the transaction. The ParentID points to the output that is getting consumed, and the UnlockConditions contain the rules for spending the output. The UnlockConditions must match the UnlockHash of the output.

func (SiacoinInput) MarshalSia

func (sci SiacoinInput) MarshalSia(w io.Writer) error

MarshalSia implements the encoding.SiaMarshaler interface.

func (*SiacoinInput) UnmarshalSia

func (sci *SiacoinInput) UnmarshalSia(r io.Reader) error

UnmarshalSia implements the encoding.SiaUnmarshaler interface.

type SiacoinOutput

type SiacoinOutput struct {
	Value      Currency   `json:"value"`
	UnlockHash UnlockHash `json:"unlockhash"`
}

A SiacoinOutput holds a volume of siacoins. Outputs must be spent atomically; that is, they must all be spent in the same transaction. The UnlockHash is the hash of the UnlockConditions that must be fulfilled in order to spend the output.

func (SiacoinOutput) MarshalSia

func (sco SiacoinOutput) MarshalSia(w io.Writer) error

MarshalSia implements the encoding.SiaMarshaler interface.

func (*SiacoinOutput) UnmarshalSia

func (sco *SiacoinOutput) UnmarshalSia(r io.Reader) error

UnmarshalSia implements the encoding.SiaUnmarshaler interface.

type SiacoinOutputID

type SiacoinOutputID crypto.Hash

SiacoinOutputID uniquely identifies a siacoin output

func (SiacoinOutputID) MarshalJSON

func (scoid SiacoinOutputID) MarshalJSON() ([]byte, error)

MarshalJSON marshals an id as a hex string.

func (SiacoinOutputID) String

func (scoid SiacoinOutputID) String() string

String prints the id in hex.

func (*SiacoinOutputID) UnmarshalJSON

func (scoid *SiacoinOutputID) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes the json hex string of the id.

type Specifier

type Specifier [SpecifierLen]byte

A Specifier is a fixed-length byte-array that serves two purposes. In the wire protocol, they are used to identify a particular encoding algorithm, signature algorithm, etc. This allows nodes to communicate on their own terms; for example, to reduce bandwidth costs, a node might only accept compressed messages.

Internally, Specifiers are used to guarantee unique IDs. Various consensus types have an associated ID, calculated by hashing the data contained in the type. By prepending the data with Specifier, we can guarantee that distinct types will never produce the same hash.

func (Specifier) MarshalJSON

func (s Specifier) MarshalJSON() ([]byte, error)

MarshalJSON marshals a specifier as a string.

func (Specifier) String

func (s Specifier) String() string

String returns the specifier as a string, trimming any trailing zeros.

func (*Specifier) UnmarshalJSON

func (s *Specifier) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes the json string of the specifier.

type StdClock

type StdClock struct{}

StdClock is an implementation of Clock that retrieves the current time using the system time.

func (StdClock) Now

func (c StdClock) Now() Timestamp

Now retrieves the current timestamp.

type StorageProof

type StorageProof struct {
	ParentID FileContractID           `json:"parentid"`
	Segment  [crypto.SegmentSize]byte `json:"segment"`
	HashSet  []crypto.Hash            `json:"hashset"`
}

A StorageProof fulfills a FileContract. The proof contains a specific segment of the file, along with a set of hashes from the file's Merkle tree. In combination, these can be used to prove that the segment came from the file. To prevent abuse, the segment must be chosen randomly, so the ID of block 'WindowStart' - 1 is used as a seed value; see StorageProofSegment for the exact implementation.

A transaction with a StorageProof cannot have any SiacoinOutputs, or FileContracts. This is because a mundane reorg can invalidate the proof, and with it the rest of the transaction.

func (*StorageProof) MarshalSia

func (sp *StorageProof) MarshalSia(w io.Writer) error

MarshalSia implements the encoding.SiaMarshaler interface.

func (*StorageProof) UnmarshalSia

func (sp *StorageProof) UnmarshalSia(r io.Reader) error

UnmarshalSia implements the encoding.SiaUnmarshaler interface.

type StratumNotification

type StratumNotification struct {
	Method string        `json:"method"`
	Params []interface{} `json:"params"`
}

StratumNotification is a special kind of Request, it has no ID and is sent from the server to the client

type StratumRequest

type StratumRequest struct {
	ID     uint64        `json:"id"`
	Method string        `json:"method"`
	Params []interface{} `json:"params"`
}

StratumRequest contains stratum request messages received over TCP request : A remote method is invoked by sending a request to the remote stratum service.

type StratumResponse

type StratumResponse struct {
	ID                  uint64        `json:"id"`
	Result              interface{}   `json:"result"`
	Error               []interface{} `json:"error"`
	StratumNotification `json:",inline"`
}

StratumResponse contains stratum response messages sent over TCP notification is an inline struct to easily decode messages in a response/notification using a json marshaller

type Target

type Target crypto.Hash

A Target is a hash that a block's ID must be "less than" in order for the block to be considered valid. Miners vary the block's 'Nonce' field in order to brute-force such an ID. The inverse of a Target is called the "difficulty," because it is proportional to the amount of time required to brute-force the Target.

func IntToTarget

func IntToTarget(i *big.Int) (t Target)

IntToTarget converts a big.Int to a Target. Negative inputs trigger a panic.

func RatToTarget

func RatToTarget(r *big.Rat) (t Target)

RatToTarget converts a big.Rat to a Target.

func (Target) AddDifficulties

func (x Target) AddDifficulties(y Target) (t Target)

AddDifficulties returns the resulting target with the difficulty of 'x' and 'y' are added together. Note that the difficulty is the inverse of the target. The sum is defined by:

sum(x, y) = 1/(1/x + 1/y)

func (Target) Cmp

func (x Target) Cmp(y Target) int

Cmp compares the difficulties of two targets. Note that the difficulty is the inverse of the target. The results are as follows:

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

func (Target) Difficulty

func (x Target) Difficulty() Currency

Difficulty returns the difficulty associated with a given target.

func (Target) Int

func (x Target) Int() *big.Int

Int converts a Target to a big.Int.

func (Target) Inverse

func (x Target) Inverse() *big.Rat

Inverse returns the inverse of a Target as a big.Rat

func (Target) MulDifficulty

func (x Target) MulDifficulty(y *big.Rat) (t Target)

MulDifficulty multiplies the difficulty of a target by y. The product is defined by: y / x

func (Target) Rat

func (x Target) Rat() *big.Rat

Rat converts a Target to a big.Rat.

func (Target) SubtractDifficulties

func (x Target) SubtractDifficulties(y Target) (t Target)

SubtractDifficulties returns the resulting target with the difficulty of 'x' is subtracted from the target with difficulty 'y'. Note that the difficulty is the inverse of the target. The difference is defined by:

sum(x, y) = 1/(1/x - 1/y)

type Timestamp

type Timestamp uint64

Timestamp is a Unix timestamp, i.e. the number of the seconds since Jan 1 1970.

func CurrentTimestamp

func CurrentTimestamp() Timestamp

CurrentTimestamp returns the current time as a Timestamp.

type TimestampSlice

type TimestampSlice []Timestamp

TimestampSlice is an array of timestamps

func (TimestampSlice) Len

func (ts TimestampSlice) Len() int

Len is part of sort.Interface

func (TimestampSlice) Less

func (ts TimestampSlice) Less(i, j int) bool

Less is part of sort.Interface

func (TimestampSlice) Swap

func (ts TimestampSlice) Swap(i, j int)

Swap is part of sort.Interface

type Transaction

type Transaction struct {
	SiacoinInputs         []SiacoinInput         `json:"siacoininputs"`
	SiacoinOutputs        []SiacoinOutput        `json:"siacoinoutputs"`
	FileContracts         []FileContract         `json:"filecontracts"`
	FileContractRevisions []FileContractRevision `json:"filecontractrevisions"`
	StorageProofs         []StorageProof         `json:"storageproofs"`
	MinerFees             []Currency             `json:"minerfees"`
	ArbitraryData         [][]byte               `json:"arbitrarydata"`
	TransactionSignatures []TransactionSignature `json:"transactionsignatures"`
}

A Transaction is an atomic component of a block. Transactions can contain inputs and outputs, file contracts, storage proofs, and even arbitrary data. They can also contain signatures to prove that a given party has approved the transaction, or at least a particular subset of it.

Transactions can depend on other previous transactions in the same block, but transactions cannot spend outputs that they create or otherwise be self-dependent.

func TransactionGraph

func TransactionGraph(sourceOutput SiacoinOutputID, edges []TransactionGraphEdge) ([]Transaction, error)

TransactionGraph will return a set of valid transactions that all spend outputs according to the input graph. Each [source, dest] pair defines an edge of the graph. The graph must be fully connected and the granparent of the graph must be the sourceOutput. '0' refers to an edge from the source output. Each edge also specifies a value for the output, and an amount of fees. If the fees are zero, no fees will be added for that edge. 'sources' must be sorted.

Example of acceptable input:

sourceOutput: // a valid siacoin output spending to UnlockConditions{}.UnlockHash()

Sources: [0, 0, 1, 2, 3, 3, 3, 4] Dests: [1, 2, 3, 3, 4, 4, 5, 6]

Resulting Graph:

  o
 / \
o   o
 \ /
  o
 /|\
 \| \
  o  x // 'x' transactions are symbolic, not actually created
  |
  x

func (Transaction) FileContractID

func (t Transaction) FileContractID(i uint64) FileContractID

FileContractID returns the ID of a file contract at the given index, which is calculated by hashing the concatenation of the FileContract Specifier, all of the fields in the transaction (except the signatures), and the contract index.

func (Transaction) ID

func (t Transaction) ID() TransactionID

ID returns the id of a transaction, which is taken by marshalling all of the fields except for the signatures and taking the hash of the result.

func (Transaction) MarshalSia

func (t Transaction) MarshalSia(w io.Writer) error

MarshalSia implements the encoding.SiaMarshaler interface.

func (Transaction) MarshalSiaNoSignatures

func (t Transaction) MarshalSiaNoSignatures(w io.Writer)

MarshalSiaNoSignatures is a wrapper used for the miningpool module. NOTE: Remove it when will be not needed

func (Transaction) MarshalSiaSize

func (t Transaction) MarshalSiaSize() (size int)

MarshalSiaSize returns the encoded size of t.

func (Transaction) SiacoinOutputID

func (t Transaction) SiacoinOutputID(i uint64) SiacoinOutputID

SiacoinOutputID returns the ID of a siacoin output at the given index, which is calculated by hashing the concatenation of the SiacoinOutput Specifier, all of the fields in the transaction (except the signatures), and output index.

func (Transaction) SiacoinOutputSum

func (t Transaction) SiacoinOutputSum() (sum Currency)

SiacoinOutputSum returns the sum of all the siacoin outputs in the transaction, which must match the sum of all the siacoin inputs. Siacoin outputs created by storage proofs are not considered, as they were considered when the contract responsible for funding them was created.

func (Transaction) SigHash

func (t Transaction) SigHash(i int) (hash crypto.Hash)

SigHash returns the hash of the fields in a transaction covered by a given signature. See CoveredFields for more details.

func (Transaction) StandaloneValid

func (t Transaction) StandaloneValid(currentHeight BlockHeight) (err error)

StandaloneValid returns an error if a transaction is not valid in any context, for example if the same output is spent twice in the same transaction. StandaloneValid will not check that all outputs being spent are legal outputs, as it has no confirmed or unconfirmed set to look at.

func (*Transaction) UnmarshalSia

func (t *Transaction) UnmarshalSia(r io.Reader) error

UnmarshalSia implements the encoding.SiaUnmarshaler interface.

type TransactionGraphEdge

type TransactionGraphEdge struct {
	Dest   int
	Fee    Currency
	Source int
	Value  Currency
}

TransactionGraphEdge defines an edge in a TransactionGraph, containing a source transaction, a destination transaction, a value, and a miner fee.

type TransactionID

type TransactionID crypto.Hash

TransactionID uniquely identifies a transaction

func (TransactionID) MarshalJSON

func (tid TransactionID) MarshalJSON() ([]byte, error)

MarshalJSON marshals an id as a hex string.

func (TransactionID) String

func (tid TransactionID) String() string

String prints the id in hex.

func (*TransactionID) UnmarshalJSON

func (tid *TransactionID) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes the json hex string of the id.

type TransactionSignature

type TransactionSignature struct {
	ParentID       crypto.Hash   `json:"parentid"`
	PublicKeyIndex uint64        `json:"publickeyindex"`
	Timelock       BlockHeight   `json:"timelock"`
	CoveredFields  CoveredFields `json:"coveredfields"`
	Signature      []byte        `json:"signature"`
}

A TransactionSignature is a signature that is included in the transaction. The signature should correspond to a public key in one of the UnlockConditions of the transaction. This key is specified first by 'ParentID', which specifies the UnlockConditions, and then 'PublicKeyIndex', which indicates the key in the UnlockConditions. There are two types that use UnlockConditions: SiacoinInputs and FileContractTerminations. Each of these types also references a ParentID, and this is the hash that 'ParentID' must match. The 'Timelock' prevents the signature from being used until a certain height. 'CoveredFields' indicates which parts of the transaction are being signed; see CoveredFields.

func (TransactionSignature) MarshalSia

func (ts TransactionSignature) MarshalSia(w io.Writer) error

MarshalSia implements the encoding.SiaMarshaler interface.

func (*TransactionSignature) UnmarshalSia

func (ts *TransactionSignature) UnmarshalSia(r io.Reader) error

UnmarshalSia implements the encoding.SiaUnmarshaler interface.

type UnlockConditions

type UnlockConditions struct {
	Timelock           BlockHeight    `json:"timelock"`
	PublicKeys         []SiaPublicKey `json:"publickeys"`
	SignaturesRequired uint64         `json:"signaturesrequired"`
}

UnlockConditions are a set of conditions which must be met to execute certain actions, such as spending a SiacoinOutput or terminating a FileContract.

The simplest requirement is that the block containing the UnlockConditions must have a height >= 'Timelock'.

'PublicKeys' specifies the set of keys that can be used to satisfy the UnlockConditions; of these, at least 'SignaturesRequired' unique keys must sign the transaction. The keys that do not need to use the same cryptographic algorithm.

If 'SignaturesRequired' == 0, the UnlockConditions are effectively "anyone can unlock." If 'SignaturesRequired' > len('PublicKeys'), then the UnlockConditions cannot be fulfilled under any circumstances.

func (UnlockConditions) MarshalSia

func (uc UnlockConditions) MarshalSia(w io.Writer) error

MarshalSia implements the encoding.SiaMarshaler interface.

func (UnlockConditions) MarshalSiaSize

func (uc UnlockConditions) MarshalSiaSize() (size int)

MarshalSiaSize returns the encoded size of uc.

func (UnlockConditions) UnlockHash

func (uc UnlockConditions) UnlockHash() UnlockHash

UnlockHash calculates the root hash of a Merkle tree of the UnlockConditions object. The leaves of this tree are formed by taking the hash of the timelock, the hash of the public keys (one leaf each), and the hash of the number of signatures. The keys are put in the middle because Timelock and SignaturesRequired are both low entropy fields; they can be protected by having random public keys next to them.

func (*UnlockConditions) UnmarshalSia

func (uc *UnlockConditions) UnmarshalSia(r io.Reader) error

UnmarshalSia implements the encoding.SiaUnmarshaler interface.

type UnlockHash

type UnlockHash crypto.Hash

An UnlockHash is a specially constructed hash of the UnlockConditions type. "Locked" values can be unlocked by providing the UnlockConditions that hash to a given UnlockHash. See UnlockConditions.UnlockHash for details on how the UnlockHash is constructed.

func (*UnlockHash) LoadString

func (uh *UnlockHash) LoadString(strUH string) error

LoadString loads a hex representation (including checksum) of an unlock hash into an unlock hash object. An error is returned if the string is invalid or fails the checksum.

func (UnlockHash) MarshalJSON

func (uh UnlockHash) MarshalJSON() ([]byte, error)

MarshalJSON is implemented on the unlock hash to always produce a hex string upon marshalling.

func (*UnlockHash) Scan

func (uh *UnlockHash) Scan(s fmt.ScanState, ch rune) error

Scan implements the fmt.Scanner interface, allowing UnlockHash values to be scanned from text.

func (UnlockHash) String

func (uh UnlockHash) String() string

String returns the hex representation of the unlock hash as a string - this includes a checksum.

func (*UnlockHash) UnmarshalJSON

func (uh *UnlockHash) UnmarshalJSON(b []byte) error

UnmarshalJSON is implemented on the unlock hash to recover an unlock hash that has been encoded to a hex string.

Jump to

Keyboard shortcuts

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