types

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: May 12, 2015 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
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
)
View Source
var (
	ZeroCurrency = NewCurrency64(0)

	ErrNegativeCurrency = errors.New("negative currency not allowed")
)
View Source
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")
	ErrWholeTransactionViolation = errors.New("covered fields violation")

	ZeroUnlockHash = UnlockHash{0}
)
View Source
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.

View Source
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")
)
View Source
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

func (b Block) CheckTarget(target Target) bool

CheckTarget returns true if the block's ID meets the given target.

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().

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 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 BlockID

type BlockID crypto.Hash

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

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 (c 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) Div

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

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

func (Currency) IsZero

func (c 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() []byte

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) Mul

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

Mul 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) RoundDown

func (x Currency) RoundDown(y uint64) (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) 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(b []byte)

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

type FileContractID crypto.Hash

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

type SiaPublicKey struct {
	Algorithm Specifier
	Key       string
}

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

type SiacoinOutputID crypto.Hash

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 Siafund

type Siafund Currency // arbitrary-precision unsigned integer

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

type SiafundOutputID crypto.Hash

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 Signature

type Signature string

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

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) Add

func (x Target) Add(y Target) (t Target)

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

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) Int

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

Int converts a Target to a big.Int.

func (Target) Inverse

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

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

func (Target) Mul

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

Mul multiplies the difficulty of a target by y. The product is defined by:

y / x

func (Target) Rat

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

Rat converts a Target to a big.Rat.

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) 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
	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

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 SpendConditions.UnlockHash for details on how the UnlockHash is constructed.

Jump to

Keyboard shortcuts

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