Documentation ¶
Index ¶
- Variables
- type Block
- type BlockHeight
- type BlockID
- type CoveredFields
- type Currency
- func (x Currency) Add(y Currency) (c Currency)
- func (c Currency) Big() *big.Int
- func (x Currency) Cmp(y Currency) int
- func (x Currency) Div(y Currency) (c Currency)
- func (c Currency) IsZero() bool
- func (c Currency) MarshalJSON() ([]byte, error)
- func (c Currency) MarshalSia() []byte
- func (x Currency) Mul(y Currency) (c Currency)
- func (x Currency) MulFloat(y float64) (c Currency)
- func (x Currency) RoundDown(y uint64) (c Currency)
- func (c *Currency) Scan(s fmt.ScanState, ch rune) error
- func (x Currency) Sqrt() (c Currency)
- func (c Currency) String() string
- func (x Currency) Sub(y Currency) (c Currency)
- func (c *Currency) UnmarshalJSON(b []byte) error
- func (c *Currency) UnmarshalSia(b []byte)
- type FileContract
- type FileContractID
- type FileContractRevision
- type SiaPublicKey
- type SiacoinInput
- type SiacoinOutput
- type SiacoinOutputID
- type Siafund
- type SiafundInput
- type SiafundOutput
- type SiafundOutputID
- type Signature
- type Specifier
- type StorageProof
- type Target
- type Timestamp
- type TimestampSlice
- type Transaction
- func (t Transaction) FileContractID(i int) FileContractID
- func (t Transaction) ID() crypto.Hash
- func (t Transaction) SiacoinOutputID(i int) SiacoinOutputID
- func (t Transaction) SiacoinOutputSum() (sum Currency)
- func (t Transaction) SiafundOutputID(i int) SiafundOutputID
- func (t Transaction) SigHash(i int) crypto.Hash
- func (t Transaction) StandaloneValid(currentHeight BlockHeight) (err error)
- type TransactionSignature
- type UnlockConditions
- type UnlockHash
Constants ¶
This section is empty.
Variables ¶
var ( BlockSizeLimit uint64 BlockFrequency BlockHeight TargetWindow BlockHeight MedianTimestampWindow int FutureThreshold Timestamp SiafundCount uint64 SiafundPortion float64 InitialCoinbase uint64 MinimumCoinbase uint64 RenterZeroConfDelay time.Duration // TODO: This shouldn't exist here. MaturityDelay BlockHeight GenesisTimestamp Timestamp GenesisSiafundUnlockHash = ZeroUnlockHash GenesisClaimUnlockHash = ZeroUnlockHash RootTarget Target RootDepth Target MaxAdjustmentUp *big.Rat MaxAdjustmentDown *big.Rat CoinbaseAugment *big.Int )
var ( ZeroCurrency = NewCurrency64(0) ErrNegativeCurrency = errors.New("negative currency not allowed") )
var ( // These Specifiers enumerate the types of signatures that are recognized // by this implementation. If a signature's type is unrecognized, the // signature is treated as valid. Signatures using the special "entropy" // type are always treated as invalid; see Consensus.md for more details. SignatureEntropy = Specifier{'e', 'n', 't', 'r', 'o', 'p', 'y'} SignatureEd25519 = Specifier{'e', 'd', '2', '5', '5', '1', '9'} ErrEntropyKey = errors.New("transaction tries to sign an entproy public key") ErrFrivilousSignature = errors.New("transaction contains a frivilous siganture") ErrInvalidPubKeyIndex = errors.New("transaction contains a signature that points to a nonexistent public key") ErrMissingSignatures = errors.New("transaction has inputs with missing signatures") ErrPrematureSignature = errors.New("timelock on signature has not expired") ErrPublicKeyOveruse = errors.New("public key was used multiple times while signing transaction") ErrSortedUniqueViolation = errors.New("sorted unique violation") ErrUnlockHashWrongLen = errors.New("marshalled unlock hash is the wrong length") ErrWholeTransactionViolation = errors.New("covered fields violation") ZeroUnlockHash = UnlockHash{0} )
var ( SpecifierSiacoinOutput = Specifier{'s', 'i', 'a', 'c', 'o', 'i', 'n', ' ', 'o', 'u', 't', 'p', 'u', 't'} SpecifierFileContract = Specifier{'f', 'i', 'l', 'e', ' ', 'c', 'o', 'n', 't', 'r', 'a', 'c', 't'} SpecifierFileContractTerminationPayout = Specifier{'f', 'i', 'l', 'e', ' ', 'c', 'o', 'n', 't', 'r', 'a', 'c', 't', ' ', 't'} SpecifierStorageProofOutput = Specifier{'s', 't', 'o', 'r', 'a', 'g', 'e', ' ', 'p', 'r', 'o', 'o', 'f'} SpecifierSiafundOutput = Specifier{'s', 'i', 'a', 'f', 'u', 'n', 'd', ' ', 'o', 'u', 't', 'p', 'u', 't'} )
These Specifiers are used internally when calculating a type's ID. See Specifier for more details.
var ( ErrDoubleSpend = errors.New("transaction uses a parent object twice") ErrFileContractWindowEndViolation = errors.New("file contract window must end at least one block after it starts") ErrFileContractWindowStartViolation = errors.New("file contract window must start in the future") ErrFileContractOutputSumViolation = errors.New("file contract has invalid output sums") ErrNonZeroClaimStart = errors.New("transaction has a siafund output with a non-zero siafund claim") ErrNonZeroRevision = errors.New("new file contract has a nonzero revision number") ErrStorageProofWithOutputs = errors.New("transaction has both a storage proof and other outputs") ErrTimelockNotSatisfied = errors.New("timelock has not been met") ErrTransactionTooLarge = errors.New("transaction is too large to fit in a block") ErrZeroOutput = errors.New("transaction cannot have an output or payout that has zero value") ErrZeroRevision = errors.New("transaction has a file contract revision with RevisionNumber=0") )
var (
ErrNegativeTarget = errors.New("negative value used when converting to target")
)
Functions ¶
This section is empty.
Types ¶
type Block ¶
type Block struct { ParentID BlockID Nonce uint64 Timestamp Timestamp MinerPayouts []SiacoinOutput Transactions []Transaction }
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) CheckTarget ¶
CheckTarget returns true if the block's ID meets the given target.
func (Block) ID ¶
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().
func (Block) MerkleRoot ¶
MerkleRoot calculates the Merkle root of a Block. The leaves of the Merkle tree are composed of the Timestamp, the miner outputs (one leaf per payout), and the transactions (one leaf per transaction).
func (Block) MinerPayoutID ¶
func (b Block) MinerPayoutID(i int) 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.
type BlockHeight ¶
type BlockHeight uint64
type CoveredFields ¶
type CoveredFields struct { WholeTransaction bool SiacoinInputs []uint64 SiacoinOutputs []uint64 FileContracts []uint64 FileContractRevisions []uint64 StorageProofs []uint64 SiafundInputs []uint64 SiafundOutputs []uint64 MinerFees []uint64 ArbitraryData []uint64 TransactionSignatures []uint64 }
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).
type Currency ¶
type Currency struct {
// contains filtered or unexported fields
}
A Currency represents a number of siacoins or siafunds. 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) (c Currency)
CalculateCoinbase calculates the coinbase for a given height. The coinbase equation is:
coinbase := max(InitialCoinbase - height, MinimumCoinbase) * CoinbaseAugment
func NewCurrency ¶
NewCurrency creates a Currency value from a big.Int. Undefined behavior occurs if a negative input is used.
func NewCurrency64 ¶
NewCurrency64 creates a Currency value from a uint64.
func (Currency) Big ¶
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 ¶
Cmp compares two Currency values. The return value follows the convention of math/big.
func (Currency) MarshalJSON ¶
MarshalJSON implements the json.Marshaler interface.
func (Currency) MarshalSia ¶
MarshalSia implements the encoding.SiaMarshaler interface. It returns the byte-slice representation of the Currency's internal big.Int. 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) MulFloat ¶
MulFloat returns a new Currency value y = c * x, where x is a float64. Behavior is undefined when x is negative.
func (*Currency) Scan ¶
Scan implements the fmt.Scanner interface, allowing Currency values to be scanned from text.
func (Currency) Sqrt ¶
Sqrt returns a new Currency value y = sqrt(c). Result is rounded down to the nearest integer.
func (*Currency) UnmarshalJSON ¶
UnmarshalJSON implements the json.Unmarshaler interface. An error is returned if a negative number is provided.
func (*Currency) UnmarshalSia ¶
UnmarshalSia implements the encoding.SiaUnmarshaler interface.
type FileContract ¶
type FileContract struct { FileSize uint64 FileMerkleRoot crypto.Hash WindowStart BlockHeight WindowEnd BlockHeight Payout Currency ValidProofOutputs []SiacoinOutput MissedProofOutputs []SiacoinOutput UnlockHash UnlockHash RevisionNumber uint64 }
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' must equal 'Payout', and the sum of 'ValidProofOutputs' must equal 'Payout' plus the siafund fee. This fee is sent to the siafund pool, which is a set of siacoins only spendable by siafund owners.
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) Tax ¶
func (fc FileContract) Tax() Currency
Tax returns the amount of Currency that will be taxed from fc.
type FileContractID ¶
func (FileContractID) FileContractTerminationPayoutID ¶
func (fcid FileContractID) FileContractTerminationPayoutID(i int) SiacoinOutputID
FileContractTerminationPayoutID returns the ID of a file contract termination payout, given the index of the payout in the termination. The ID is calculated by hashing the concatenation of the FileContractTerminationPayout Specifier, the ID of the file contract being terminated, and the payout index.
func (FileContractID) StorageProofOutputID ¶
func (fcid FileContractID) StorageProofOutputID(proofValid bool, i int) 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.
type FileContractRevision ¶
type FileContractRevision struct { ParentID FileContractID UnlockConditions UnlockConditions NewRevisionNumber uint64 NewFileSize uint64 NewFileMerkleRoot crypto.Hash NewWindowStart BlockHeight NewWindowEnd BlockHeight NewValidProofOutputs []SiacoinOutput NewMissedProofOutputs []SiacoinOutput NewUnlockHash UnlockHash }
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 valid 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.
type SiaPublicKey ¶
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.
type SiacoinInput ¶
type SiacoinInput struct { ParentID SiacoinOutputID UnlockConditions 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.
type SiacoinOutput ¶
type SiacoinOutput struct { Value Currency UnlockHash 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.
type SiacoinOutputID ¶
IDs are used to refer to a type without revealing its contents. They are constructed by hashing specific fields of the type, along with a Specifier. While all of these types are hashes, defining type aliases gives us type safety and makes the code more readable.
type SiafundInput ¶
type SiafundInput struct { ParentID SiafundOutputID UnlockConditions UnlockConditions }
A SiafundInput consumes a SiafundOutput and adds the siafunds to the set of siafunds 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.
type SiafundOutput ¶
type SiafundOutput struct { Value Currency UnlockHash UnlockHash ClaimUnlockHash UnlockHash ClaimStart Currency }
A SiafundOutput holds a volume of siafunds. Outputs must be spent atomically; that is, they must all be spent in the same transaction. The UnlockHash is the hash of a set of UnlockConditions that must be fulfilled in order to spend the output.
When the SiafundOutput is spent, a SiacoinOutput is created, where:
SiacoinOutput.Value := (SiafundPool - ClaimStart) / 10,000 SiacoinOutput.UnlockHash := SiafundOutput.ClaimUnlockHash
When a SiafundOutput is put into a transaction, the ClaimStart must always equal zero. While the transaction is being processed, the ClaimStart is set to the value of the SiafundPool.
type SiafundOutputID ¶
func (SiafundOutputID) SiaClaimOutputID ¶
func (id SiafundOutputID) SiaClaimOutputID() SiacoinOutputID
SiaClaimOutputID returns the ID of the SiacoinOutput that is created when the siafund output is spent. The ID is the hash the SiafundOutputID.
type Specifier ¶
type Specifier [16]byte
A Specifier is a fixed-length string 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.
type StorageProof ¶
type StorageProof struct { ParentID FileContractID Segment [crypto.SegmentSize]byte HashSet []crypto.Hash }
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, SiafundOutputs, or FileContracts. This is because a mundane reorg can invalidate the proof, and with it the rest of the transaction.
type Target ¶
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 ¶
IntToTarget converts a big.Int to a Target. Negative inputs trigger a panic.
func RatToTarget ¶
RatToTarget converts a big.Rat to a Target.
func (Target) Add ¶
Add 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 ¶
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
type Timestamp ¶
type Timestamp uint64
func CurrentTimestamp ¶
func CurrentTimestamp() Timestamp
CurrentTimestamp returns the current time as a Timestamp.
type TimestampSlice ¶
type TimestampSlice []Timestamp
func (TimestampSlice) Less ¶
func (ts TimestampSlice) Less(i, j int) bool
Less is part of sort.Interface
type Transaction ¶
type Transaction struct { SiacoinInputs []SiacoinInput SiacoinOutputs []SiacoinOutput FileContracts []FileContract FileContractRevisions []FileContractRevision StorageProofs []StorageProof SiafundInputs []SiafundInput SiafundOutputs []SiafundOutput MinerFees []Currency ArbitraryData []string TransactionSignatures []TransactionSignature }
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 (Transaction) FileContractID ¶
func (t Transaction) FileContractID(i int) 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() crypto.Hash
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) SiacoinOutputID ¶
func (t Transaction) SiacoinOutputID(i int) 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 and siafund outputs are not considered, as they were considered when the contract responsible for funding them was created.
func (Transaction) SiafundOutputID ¶
func (t Transaction) SiafundOutputID(i int) SiafundOutputID
SiafundOutputID returns the ID of a SiafundOutput at the given index, which is calculated by hashing the concatenation of the SiafundOutput Specifier, all of the fields in the transaction (except the signatures), and output index.
func (Transaction) SigHash ¶
func (t Transaction) SigHash(i int) 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.
type TransactionSignature ¶
type TransactionSignature struct { ParentID crypto.Hash PublicKeyIndex uint64 Timelock BlockHeight CoveredFields CoveredFields Signature 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 three types that use UnlockConditions: SiacoinInputs, SiafundInputs, 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.
type UnlockConditions ¶
type UnlockConditions struct { Timelock BlockHeight PublicKeys []SiaPublicKey SignaturesRequired uint64 }
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) 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.
type UnlockHash ¶
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 SpendConditions.UnlockHash for details on how the UnlockHash is constructed.
func (UnlockHash) MarshalJSON ¶ added in v0.3.2
func (uh UnlockHash) MarshalJSON() ([]byte, error)
MarshalJSON is implemented on the unlock hash to always produce a hex string upon marshalling.
func (*UnlockHash) UnmarshalJSON ¶ added in v0.3.2
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.