types

package
v1.5.9 Latest Latest
Warning

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

Go to latest
Published: Jul 21, 2022 License: MIT Imports: 18 Imported by: 43

Documentation

Index

Constants

View Source
const (
	// BlockHeaderSize is the size, in bytes, of a block header.
	// 32 (ParentID) + 8 (Nonce) + 8 (Timestamp) + 32 (MerkleRoot)
	BlockHeaderSize = 80
)
View Source
const SpecifierLen = 16

SpecifierLen is the length in bytes of a Specifier.

View Source
const (
	// 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
)

Variables

View Source
var (
	// ASICHardforkHeight is the height at which the hardfork targeting
	// selected ASICs was activated.
	ASICHardforkHeight BlockHeight

	// ASICHardforkTotalTarget is the initial target after the ASIC hardfork.
	// The actual target at ASICHardforkHeight is replaced with this value in
	// order to prevent intolerably slow block times post-fork.
	ASICHardforkTotalTarget Target

	// ASICHardforkTotalTime is the initial total time after the ASIC
	// hardfork. The actual total time at ASICHardforkHeight is replaced with
	// this value in order to prevent intolerably slow block times post-fork.
	ASICHardforkTotalTime int64

	// ASICHardforkFactor is the factor by which the hashrate of targeted
	// ASICs will be reduced.
	ASICHardforkFactor = uint64(1009)

	// ASICHardforkReplayProtectionPrefix is a byte that prefixes
	// SiacoinInputs and SiafundInputs when calculating SigHashes to protect
	// against replay attacks.
	ASICHardforkReplayProtectionPrefix = []byte{0}

	// FoundationHardforkReplayProtectionPrefix is a byte that prefixes
	// SiacoinInputs and SiafundInputs when calculating SigHashes to protect
	// against replay attacks.
	FoundationHardforkReplayProtectionPrefix = []byte{1}

	// 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)
	// BlocksPerHour is the number of blocks expected to be mined per hour.
	BlocksPerHour = BlockHeight(6)
	// BlocksPerDay is the number of blocks expected to be mined per day.
	BlocksPerDay = 24 * BlocksPerHour
	// BlocksPerWeek is the number of blocks expected to be mined per week.
	BlocksPerWeek = 7 * BlocksPerDay
	// BlocksPerMonth is the number of blocks expected to be mined per month.
	BlocksPerMonth = 30 * BlocksPerDay
	// BlocksPerYear is the number of blocks expected to be mined per year.
	BlocksPerYear = 365 * BlocksPerDay

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

	// FoundationHardforkHeight is the height at which the Foundation subsidy
	// hardfork was activated.
	FoundationHardforkHeight BlockHeight

	// FoundationSubsidyFrequency is the number of blocks between each
	// Foundation subsidy payout. Although the subsidy is calculated on a
	// per-block basis, it "pays out" much less frequently in order to reduce
	// the number of SiacoinOutputs created.
	FoundationSubsidyFrequency BlockHeight

	// FoundationSubsidyPerBlock is the amount allocated to the Foundation
	// subsidy per block.
	FoundationSubsidyPerBlock = SiacoinPrecision.Mul64(30e3)

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

	// GenesisSiacoinAllocation is the set of SiacoinOutputs created in the Genesis
	// block
	GenesisSiacoinAllocation []SiacoinOutput
	// GenesisSiafundAllocation is the set of SiafundOutputs created in the Genesis
	// block.
	GenesisSiafundAllocation []SiafundOutput
	// GenesisTimestamp is the timestamp when genesis block was mined
	GenesisTimestamp Timestamp
	// InitialCoinbase is the coinbase reward of the Genesis block.
	InitialCoinbase = uint64(300e3)

	// InitialFoundationUnlockHash is the primary Foundation subsidy address. It
	// receives the initial Foundation subsidy. The keys that this address was
	// derived from can also be used to set a new primary and failsafe address.
	InitialFoundationUnlockHash UnlockHash
	// InitialFoundationTestingSalt is the salt used to generate the
	// UnlockConditions and signing keys for the InitialFoundationUnlockHash.
	InitialFoundationTestingSalt = "saltgenprimary"
	// InitialFoundationFailsafeUnlockHash is the "backup" Foundation address.
	// It does not receive the Foundation subsidy, but its keys can be used to
	// set a new primary and failsafe address. These UnlockConditions should
	// also be subject to a timelock that prevents the failsafe from being used
	// immediately.
	InitialFoundationFailsafeUnlockHash UnlockHash
	// InitialFoundationFailsafeTestingSalt is the salt used to generate the
	// UnlockConditions and signing keys for the
	// InitialFoundationFailsafeUnlockHash.
	InitialFoundationFailsafeTestingSalt = "saltgenfailsafe"
	// InitialFoundationSubsidy is the one-time subsidy sent to the Foundation
	// address upon activation of the hardfork, representing one year's worth of
	// block subsidies.
	InitialFoundationSubsidy = SiacoinPrecision.Mul64(30e3).Mul64(uint64(BlocksPerYear))

	// 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. Another example is a siafund
	// payout, as a tiny reorg may change the value of the payout, and thus invalidate
	// any transactions spending the payout. 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
	// OakHardforkBlock is the height at which the hardfork to switch to the oak
	// difficulty adjustment algorithm is triggered.
	OakHardforkBlock BlockHeight
	// OakHardforkFixBlock is the height at which the hardfork to switch from the broken
	// oak difficulty adjustment algorithm to the fixed oak difficulty adjustment
	// algorithm is triggered.
	OakHardforkFixBlock BlockHeight
	// OakHardforkTxnSizeLimit is the maximum size allowed for a transaction, a change
	// which I believe was implemented simultaneously with the oak hardfork.
	OakHardforkTxnSizeLimit = 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))
	// SiafundCount is the total number of Siafunds in existence.
	SiafundCount = NewCurrency64(10000)
	// SiafundPortion is the percentage of siacoins that is taxed from FileContracts.
	SiafundPortion = big.NewRat(39, 1000)
	// 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")
	// ErrParseCurrencyAmount is returned when the input is unable to be parsed
	// into a currency unit due to a malformed amount.
	ErrParseCurrencyAmount = errors.New("malformed amount")
	// ErrParseCurrencyInteger is returned when the input is unable to be parsed
	// into a currency unit due to a non-integer value.
	ErrParseCurrencyInteger = errors.New("non-integer number of hastings")

	// ErrParseCurrencyUnits is returned when the input is unable to be parsed
	// into a currency unit due to missing units.
	ErrParseCurrencyUnits = errors.New("amount is missing currency units; run 'wallet --help' for a list of units. Currency units are case sensitive")

	// 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 (
	// ErrUnexpectedFormat is the error that is returned when the exchange rate
	// is in an unexpected format.
	ErrUnexpectedFormat = errors.New("exchange rate has unexpected format")

	// ErrZeroNotAllowed is returned when attempting to set the exchange rate to
	// zero.
	ErrZeroNotAllowed = errors.New("exchange rate cannot be zero")
)
View Source
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

	// ErrRevisionCostTooHigh indicates that a new revision can't be created
	// because the cost is higher than the available funds.
	ErrRevisionCostTooHigh = errors.New("Can't create new revision with this cost. Not enough funds remaining to cover it")

	// ErrRevisionCollateralTooLow indicates that a new revision can't be created
	// because the available collateral is too low.
	ErrRevisionCollateralTooLow = errors.New("Can't create new revision with this collateral. Not enough funds remaining to cover it")

	// ErrMissingVoidOutput is the error returned when the void output of a
	// contract or revision is accessed that no longer has one.
	ErrMissingVoidOutput = errors.New("void output is missing")

	// ErrRevisionNotIncremented is returned if the revision number wasn't
	// incremented when creating a new revision.
	ErrRevisionNotIncremented = errors.New("revision number was not incremented")
)
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 = NewSpecifier("ed25519")
	// SignatureEntropy is a specifier for entropy
	SignatureEntropy = NewSpecifier("entropy")
)
View Source
var (
	ErrTransactionIDWrongLen = errors.New("input has wrong length to be an encoded transaction id")

	SpecifierClaimOutput          = NewSpecifier("claim output")
	SpecifierFileContract         = NewSpecifier("file contract")
	SpecifierFileContractRevision = NewSpecifier("file contract re")
	SpecifierMinerFee             = NewSpecifier("miner fee")
	SpecifierMinerPayout          = NewSpecifier("miner payout")
	SpecifierSiacoinInput         = NewSpecifier("siacoin input")
	SpecifierSiacoinOutput        = NewSpecifier("siacoin output")
	SpecifierSiafundInput         = NewSpecifier("siafund input")
	SpecifierSiafundOutput        = NewSpecifier("siafund output")
	SpecifierStorageProofOutput   = NewSpecifier("storage proof")
)

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")
	// ErrNonZeroClaimStart is an error when a transaction has a siafund
	// output with a non-zero siafund claim
	ErrNonZeroClaimStart = errors.New("transaction has a siafund output with a non-zero siafund claim")
	// 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")
	// ErrInvalidFoundationUpdateEncoding is returned when a transaction
	// contains an improperly-encoded FoundationUnlockHashUpdate
	ErrInvalidFoundationUpdateEncoding = errors.New("transaction contains an improperly-encoded FoundationUnlockHashUpdate")
	// ErrUninitializedFoundationUpdate is returned when a transaction contains
	// an uninitialized FoundationUnlockHashUpdate. To prevent accidental
	// misuse, updates cannot set the Foundation addresses to the empty ("void")
	// UnlockHash.
	ErrUninitializedFoundationUpdate = errors.New("transaction contains an uninitialized FoundationUnlockHashUpdate")
)
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")
)
View Source
var SpecifierFoundation = NewSpecifier("foundation")

SpecifierFoundation is used for calculating the OutputID of Foundation subsidy outputs. It also serves as the arbitrary data prefix when encoding FoundationUnlockHashUpdates.

View Source
var (
	// TaxHardforkHeight is the height at which the tax hardfork occurred.
	TaxHardforkHeight = build.Select(build.Var{
		Dev:      BlockHeight(10),
		Standard: BlockHeight(21e3),
		Testing:  BlockHeight(10),
	}).(BlockHeight)
)

Functions

func ParseCurrency added in v1.5.7

func ParseCurrency(amount string) (string, error)

ParseCurrency converts a siacoin amount to base units.

func RuneToString added in v1.5.7

func RuneToString(r rune) string

RuneToString converts a rune type to a string.

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) CalculateSubsidy added in v0.3.3

func (b Block) CalculateSubsidy(height BlockHeight) Currency

CalculateSubsidy takes a block and a height and determines the block subsidy.

func (Block) Header added in v0.3.3

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 added in v1.0.0

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

MarshalSia implements the encoding.SiaMarshaler interface.

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) 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 added in v1.0.0

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

UnmarshalSia implements the encoding.SiaUnmarshaler interface.

type BlockHeader added in v0.3.3

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 added in v1.0.0

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) FoundationSubsidyID added in v1.5.7

func (bid BlockID) FoundationSubsidyID() SiacoinOutputID

FoundationSubsidyID returns the ID of the Foundation subsidy, which is calculated by hashing the concatenation of the BlockID and SpecifierFoundation.

func (*BlockID) LoadString added in v1.3.3

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

LoadString loads a BlockID from a string

func (BlockID) MarshalJSON added in v1.0.0

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

MarshalJSON marshales a block id as a hex string.

func (BlockID) String added in v1.0.0

func (bid BlockID) String() string

String prints the block id in hex.

func (*BlockID) UnmarshalJSON added in v1.0.0

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

UnmarshalJSON decodes the json hex string of the block id.

type BlockNonce added in v0.3.3

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 added in v1.0.0

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"`
	SiafundInputs         []uint64 `json:"siafundinputs"`
	SiafundOutputs        []uint64 `json:"siafundoutputs"`
	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 added in v1.2.0

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

MarshalSia implements the encoding.SiaMarshaler interface.

func (CoveredFields) MarshalSiaSize added in v1.3.0

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

MarshalSiaSize returns the encoded size of cf.

func (*CoveredFields) UnmarshalSia added in v1.3.1

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

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

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

func CalculateNumSiacoins added in v1.0.0

func CalculateNumSiacoins(height BlockHeight) (total 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 PostTax added in v1.0.0

func PostTax(height BlockHeight, payout Currency) Currency

PostTax returns the amount of currency remaining in a file contract payout after tax.

func Tax added in v1.0.0

func Tax(height BlockHeight, payout Currency) Currency

Tax returns the amount of Currency that will be taxed from fc.

func (Currency) Add

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

Add returns a new Currency value c = x + y

func (Currency) Add64 added in v1.5.7

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

Add64 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 added in v1.0.4

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 added in v1.0.0

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

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

func (Currency) Equals added in v1.0.4

func (x Currency) Equals(y Currency) bool

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

func (Currency) Equals64 added in v1.0.4

func (x Currency) Equals64(y uint64) bool

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

func (Currency) Float64 added in v1.4.0

func (x Currency) Float64() (f64 float64, exact bool)

Float64 will return the types.Currency as a float64.

func (Currency) HumanString added in v1.3.0

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 added in v1.3.0

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 added in v1.0.0

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 added in v1.0.0

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) MulTax added in v1.0.0

func (x Currency) MulTax() (c Currency)

MulTax returns a new Currency value c = x * 0.039, where 0.039 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) Sub64 added in v1.5.7

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

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

func (Currency) Uint64 added in v1.0.0

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 ExchangeRate added in v1.5.7

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

ExchangeRate is represented as a float and an associated symbol.

func ParseExchangeRate added in v1.5.7

func ParseExchangeRate(s string) (*ExchangeRate, error)

ParseExchangeRate parses a string into an exchange rate. It returns nil if no valid exchange rate could be detected. If s is not an empty string and the contents could not be parsed, an error will be returned that describes the parse error.

func (*ExchangeRate) ApplyAndFormat added in v1.5.7

func (r *ExchangeRate) ApplyAndFormat(c Currency) string

ApplyAndFormat applies the exchange rate to a currency amount and formats the result. Assumes that c cannot be negative. The output will use two decimal places, expect for small values where three or four decimal places are used.

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' minus 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) MarshalSia added in v1.3.0

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

MarshalSia implements the encoding.SiaMarshaler interface.

func (FileContract) MarshalSiaSize added in v1.3.0

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

MarshalSiaSize returns the encoded size of fc.

func (FileContract) MissedHostOutput added in v1.5.7

func (fc FileContract) MissedHostOutput() SiacoinOutput

MissedHostOutput gets the host's missed proof output.

func (FileContract) MissedRenterOutput added in v1.5.7

func (fc FileContract) MissedRenterOutput() SiacoinOutput

MissedRenterOutput gets the renter's missed proof output.

func (FileContract) MissedRenterPayout added in v1.5.7

func (fc FileContract) MissedRenterPayout() Currency

MissedRenterPayout gets the value of the renter's missed proof output.

func (FileContract) MissedVoidOutput added in v1.5.7

func (fc FileContract) MissedVoidOutput() (SiacoinOutput, error)

MissedVoidOutput gets the void's missed proof output.

func (FileContract) SetMissedHostPayout added in v1.5.7

func (fc FileContract) SetMissedHostPayout(value Currency)

SetMissedHostPayout sets the value of the host's missed proof output.

func (FileContract) SetMissedRenterPayout added in v1.5.7

func (fc FileContract) SetMissedRenterPayout(value Currency)

SetMissedRenterPayout sets the value of the renter's missed proof output.

func (FileContract) SetMissedVoidPayout added in v1.5.7

func (fc FileContract) SetMissedVoidPayout(value Currency) error

SetMissedVoidPayout sets the value of the void's missed proof output.

func (FileContract) SetValidHostPayout added in v1.5.7

func (fc FileContract) SetValidHostPayout(value Currency)

SetValidHostPayout sets the value of the host's valid proof output.

func (FileContract) SetValidRenterPayout added in v1.5.7

func (fc FileContract) SetValidRenterPayout(value Currency)

SetValidRenterPayout sets the value of the renter's valid proof output.

func (FileContract) TotalPayout added in v1.5.7

func (fc FileContract) TotalPayout() (total, valid, missed Currency)

TotalPayout returns the sum of each the valid and missed payouts plus the payout field of the contract.

func (*FileContract) UnmarshalSia added in v1.3.1

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

UnmarshalSia implements the encoding.SiaUnmarshaler interface.

func (FileContract) ValidHostOutput added in v1.5.7

func (fc FileContract) ValidHostOutput() SiacoinOutput

ValidHostOutput sets gets host's missed proof output.

func (FileContract) ValidHostPayout added in v1.5.7

func (fc FileContract) ValidHostPayout() Currency

ValidHostPayout gets the value of the host's valid proof output.

func (FileContract) ValidRenterOutput added in v1.5.7

func (fc FileContract) ValidRenterOutput() SiacoinOutput

ValidRenterOutput gets the renter's valid proof output.

func (FileContract) ValidRenterPayout added in v1.5.7

func (fc FileContract) ValidRenterPayout() Currency

ValidRenterPayout gets the value of the renter's valid proof output.

type FileContractID

type FileContractID crypto.Hash

FileContractID uniquely identifies a file contract

func (*FileContractID) LoadString added in v1.3.4

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

LoadString loads a FileContractID from a string

func (FileContractID) MarshalJSON added in v1.0.0

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 added in v1.0.0

func (fcid FileContractID) String() string

String prints the id in hex.

func (*FileContractID) UnmarshalJSON added in v1.0.0

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) EAFundRevision added in v1.5.7

func (fcr FileContractRevision) EAFundRevision(amount Currency) (FileContractRevision, error)

EAFundRevision returns a copy of the revision with incremented revision number where the given amount has moved from renter to the host. This is similar to PaymentRevision but instead of moving the missed renter payout to the void it is moved to the host. That's because the money used to fund an EA should always go to the host. A contract might only be used for downloading/uploading so the merkle root might never change. Which means a storage proof can't be submitted by the host. Once the contract is used for uploading using the MDM, a separate revision will be created to move the money from the missed host output to the void.

func (FileContractRevision) EndHeight added in v1.4.0

func (fcr FileContractRevision) EndHeight() BlockHeight

EndHeight returns the height at which the host is no longer obligated to store the contract data.

func (FileContractRevision) ExecuteProgramRevision added in v1.5.7

func (fcr FileContractRevision) ExecuteProgramRevision(revisionNumber uint64, transfer Currency, newRoot crypto.Hash, newSize uint64) (FileContractRevision, error)

ExecuteProgramRevision creates a new ExecuteProgramRevision based off of an existing revision. Since the MDM program is already paid for using EAs and EA funded money is moved to the host's valid and missed output but not the void, this revision moves a certain amount of that money from the missed host output to the void for collateral and per-block storage cost in case the host can't provide a storage proof.

func (FileContractRevision) HostPublicKey added in v1.4.0

func (fcr FileContractRevision) HostPublicKey() SiaPublicKey

HostPublicKey returns the public key of the contract's host. This method will panic if called on an incomplete revision.

func (FileContractRevision) ID added in v1.4.0

ID returns the contract's ID.

func (FileContractRevision) MarshalSia added in v1.3.0

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

MarshalSia implements the encoding.SiaMarshaler interface.

func (FileContractRevision) MarshalSiaSize added in v1.3.0

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

MarshalSiaSize returns the encoded size of fcr.

func (FileContractRevision) MissedHostOutput added in v1.5.7

func (fcr FileContractRevision) MissedHostOutput() SiacoinOutput

MissedHostOutput gets the host's missed proof output.

func (FileContractRevision) MissedHostPayout added in v1.5.7

func (fcr FileContractRevision) MissedHostPayout() Currency

MissedHostPayout gets the value of the host's missed proof output.

func (FileContractRevision) MissedRenterOutput added in v1.5.7

func (fcr FileContractRevision) MissedRenterOutput() SiacoinOutput

MissedRenterOutput gets the renter's missed proof output.

func (FileContractRevision) MissedRenterPayout added in v1.5.7

func (fcr FileContractRevision) MissedRenterPayout() Currency

MissedRenterPayout gets the value of the renter's missed proof output.

func (FileContractRevision) MissedVoidOutput added in v1.5.7

func (fcr FileContractRevision) MissedVoidOutput() (SiacoinOutput, error)

MissedVoidOutput gets the void's missed proof output.

func (FileContractRevision) MissedVoidPayout added in v1.5.7

func (fcr FileContractRevision) MissedVoidPayout() (Currency, error)

MissedVoidPayout gets the void's missed proof output's value.

func (FileContractRevision) PaymentRevision added in v1.5.7

func (fcr FileContractRevision) PaymentRevision(amount Currency) (FileContractRevision, error)

PaymentRevision returns a copy of the revision with incremented revision number where the given amount has moved from the renter to the host (for valid outputs) and from renter to the void (for missed outputs).

func (FileContractRevision) SetMissedHostPayout added in v1.5.7

func (fcr FileContractRevision) SetMissedHostPayout(value Currency)

SetMissedHostPayout sets the host's missed proof output.

func (FileContractRevision) SetMissedRenterPayout added in v1.5.7

func (fcr FileContractRevision) SetMissedRenterPayout(value Currency)

SetMissedRenterPayout sets the renter's missed proof output.

func (FileContractRevision) SetMissedVoidPayout added in v1.5.7

func (fcr FileContractRevision) SetMissedVoidPayout(value Currency) error

SetMissedVoidPayout sets the void's missed proof output.

func (FileContractRevision) SetValidHostPayout added in v1.5.7

func (fcr FileContractRevision) SetValidHostPayout(value Currency)

SetValidHostPayout sets the host's valid proof output.

func (FileContractRevision) SetValidRenterPayout added in v1.5.7

func (fcr FileContractRevision) SetValidRenterPayout(value Currency)

SetValidRenterPayout sets the renter's valid proof output.

func (FileContractRevision) ToTransaction added in v1.5.7

func (fcr FileContractRevision) ToTransaction() Transaction

ToTransaction wraps the revision in a Transaction. Note that the PublicKeyIndex is hardcoded at 0 as the renter key is always first, see formContract

func (FileContractRevision) TotalPayout added in v1.5.7

func (fcr FileContractRevision) TotalPayout() (valid, missed Currency)

TotalPayout returns the sum of each the valid and missed payouts.

func (*FileContractRevision) UnmarshalSia added in v1.3.1

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

UnmarshalSia implements the encoding.SiaUnmarshaler interface.

func (FileContractRevision) ValidHostOutput added in v1.5.7

func (fcr FileContractRevision) ValidHostOutput() SiacoinOutput

ValidHostOutput sets gets host's missed proof output.

func (FileContractRevision) ValidHostPayout added in v1.5.7

func (fcr FileContractRevision) ValidHostPayout() Currency

ValidHostPayout gets the value of the host's valid proof output.

func (FileContractRevision) ValidRenterOutput added in v1.5.7

func (fcr FileContractRevision) ValidRenterOutput() SiacoinOutput

ValidRenterOutput gets the renter's valid proof output.

func (FileContractRevision) ValidRenterPayout added in v1.5.7

func (fcr FileContractRevision) ValidRenterPayout() Currency

ValidRenterPayout gets the value of the renter's valid proof output.

type FoundationUnlockHashUpdate added in v1.5.7

type FoundationUnlockHashUpdate struct {
	NewPrimary  UnlockHash
	NewFailsafe UnlockHash
}

A FoundationUnlockHashUpdate directs the consensus set to update its Foundation-related UnlockHashes. Updates are submitted to the chain via the ArbitraryData field of a transaction.

type OutputID added in v1.0.0

type OutputID crypto.Hash

OutputID uniquely identifies an output

func (OutputID) MarshalJSON added in v1.0.0

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

MarshalJSON marshals an id as a hex string.

func (OutputID) String added in v1.0.0

func (oid OutputID) String() string

String prints the id in hex.

func (*OutputID) UnmarshalJSON added in v1.0.0

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

UnmarshalJSON decodes the json hex string of the id.

type ProofStatus added in v0.3.3

type ProofStatus bool

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

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 added in v1.2.0

func Ed25519PublicKey(pk crypto.PublicKey) SiaPublicKey

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

func (SiaPublicKey) Equals added in v1.5.7

func (x SiaPublicKey) Equals(y SiaPublicKey) bool

Equals compares two SiaPublicKey types for equality

func (*SiaPublicKey) LoadString added in v1.1.1

func (spk *SiaPublicKey) LoadString(s string) error

LoadString is the inverse of SiaPublicKey.String().

func (SiaPublicKey) MarshalSia added in v1.2.0

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

MarshalSia implements the encoding.SiaMarshaler interface.

func (SiaPublicKey) ShortString added in v1.5.7

func (spk SiaPublicKey) ShortString() string

ShortString is a convenience function that returns a representation of the public key that can be used for logging or debugging. It returns the first 16 bytes of the actual key hex encoded.

NOTE: this function should only be used for testing and/or debugging purposes, do not use this key representation as key in a map for instance.

func (SiaPublicKey) String added in v1.0.3

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) ToPublicKey added in v1.5.7

func (x SiaPublicKey) ToPublicKey() (pk crypto.PublicKey)

ToPublicKey converts the SiaPublicKey into a crypto.PublicKey

func (*SiaPublicKey) UnmarshalJSON added in v1.3.5

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

UnmarshalJSON unmarshals a SiaPublicKey as JSON.

func (*SiaPublicKey) UnmarshalSia added in v1.3.1

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 added in v1.2.0

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

MarshalSia implements the encoding.SiaMarshaler interface.

func (*SiacoinInput) UnmarshalSia added in v1.3.1

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 added in v1.2.0

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

MarshalSia implements the encoding.SiaMarshaler interface.

func (*SiacoinOutput) UnmarshalSia added in v1.3.1

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 added in v1.0.0

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

MarshalJSON marshals an id as a hex string.

func (SiacoinOutputID) String added in v1.0.0

func (scoid SiacoinOutputID) String() string

String prints the id in hex.

func (*SiacoinOutputID) UnmarshalJSON added in v1.0.0

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

UnmarshalJSON decodes the json hex string of the id.

type SiafundInput

type SiafundInput struct {
	ParentID         SiafundOutputID  `json:"parentid"`
	UnlockConditions UnlockConditions `json:"unlockconditions"`
	ClaimUnlockHash  UnlockHash       `json:"claimunlockhash"`
}

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.

func (SiafundInput) MarshalSia added in v1.2.0

func (sfi SiafundInput) MarshalSia(w io.Writer) error

MarshalSia implements the encoding.SiaMarshaler interface.

func (*SiafundInput) UnmarshalSia added in v1.3.1

func (sfi *SiafundInput) UnmarshalSia(r io.Reader) error

UnmarshalSia implements the encoding.SiaUnmarshaler interface.

type SiafundOutput

type SiafundOutput struct {
	Value      Currency   `json:"value"`
	UnlockHash UnlockHash `json:"unlockhash"`
	ClaimStart Currency   `json:"claimstart"`
}

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 * Value
SiacoinOutput.UnlockHash := SiafundInput.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.

func (SiafundOutput) MarshalSia added in v1.2.0

func (sfo SiafundOutput) MarshalSia(w io.Writer) error

MarshalSia implements the encoding.SiaMarshaler interface.

func (*SiafundOutput) UnmarshalSia added in v1.3.1

func (sfo *SiafundOutput) UnmarshalSia(r io.Reader) error

UnmarshalSia implements the encoding.SiaUnmarshaler interface.

type SiafundOutputID

type SiafundOutputID crypto.Hash

SiafundOutputID uniquely identifies a siafund output

func (SiafundOutputID) MarshalJSON added in v1.0.0

func (sfoid SiafundOutputID) MarshalJSON() ([]byte, error)

MarshalJSON marshals an id as a hex string.

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.

func (SiafundOutputID) String added in v1.0.0

func (sfoid SiafundOutputID) String() string

String prints the id in hex.

func (*SiafundOutputID) UnmarshalJSON added in v1.0.0

func (sfoid *SiafundOutputID) 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 NewSpecifier added in v1.5.7

func NewSpecifier(name string) Specifier

NewSpecifier returns a specifier for given name, a specifier can only be 16 bytes so we panic if the given name is too long.

func (Specifier) MarshalJSON added in v1.0.0

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

MarshalJSON marshals a specifier as a string.

func (Specifier) MarshalText added in v1.5.7

func (t Specifier) MarshalText() (text []byte, err error)

MarshalText implements the TextMarshaler interface

func (Specifier) String added in v1.0.0

func (s Specifier) String() string

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

func (*Specifier) UnmarshalJSON added in v1.0.0

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

UnmarshalJSON decodes the json string of the specifier.

func (*Specifier) UnmarshalText added in v1.5.7

func (t *Specifier) UnmarshalText(text []byte) error

UnmarshalText implements the TextUnmarshaler interface

type StdClock added in v1.0.0

type StdClock struct{}

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

func (StdClock) Now added in v1.0.0

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, SiafundOutputs, or FileContracts. This is because a mundane reorg can invalidate the proof, and with it the rest of the transaction.

func (*StorageProof) MarshalSia added in v1.3.0

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

MarshalSia implements the encoding.SiaMarshaler interface.

func (*StorageProof) UnmarshalSia added in v1.3.1

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

UnmarshalSia implements the encoding.SiaUnmarshaler interface.

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 added in v0.3.3

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 added in v1.0.0

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 added in v0.3.3

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 added in v1.0.0

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"`
	SiafundInputs         []SiafundInput         `json:"siafundinputs"`
	SiafundOutputs        []SiafundOutput        `json:"siafundoutputs"`
	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 added in v1.3.2

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

TransactionGraph will take a set of edges as input and use those edges to create a transaction graph. The code interprets the edges as going from a source node to a sink node. For all nodes, all of the inputs will be part of the same transaction. And for all nodes, all of the outputs will be part of the same transaction. For nodes that have only outputs (the source node, node 0), these nodes will appear in only one transaction. And for nodes that have only inputs (the sink nodes), these nodes will also only appear in one transaction.

Two nodes will only appear in the same transaction if required to satisfy the above requirements, otherwise the nodes will be created using distinct transactions.

Node zero will use the 'sourceOutput' as its input, and is the only node that is allowed to have no inputs specified.

Example Input:

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

This graph will result in 4 transactions:

t1: [0->1],[0->2]
t2: [1->3],[2->3]
t3: [3->4],[3->4],[3->5]
t4: [4->6]

NOTE: the edges must be specified so that the inputs and outputs of the resulting transaction add up correctly.

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) HostSignature added in v1.5.7

func (t Transaction) HostSignature() TransactionSignature

HostSignature returns the host's transaction signature

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 added in v1.2.0

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

MarshalSia implements the encoding.SiaMarshaler interface.

func (Transaction) MarshalSiaSize added in v1.3.0

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

MarshalSiaSize returns the encoded size of t.

func (Transaction) RenterSignature added in v1.5.7

func (t Transaction) RenterSignature() TransactionSignature

RenterSignature returns the host's transaction signature

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 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 uint64) 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, height BlockHeight) (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 added in v1.3.1

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

UnmarshalSia implements the encoding.SiaUnmarshaler interface.

type TransactionGraphEdge added in v1.3.2

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 added in v1.0.0

type TransactionID crypto.Hash

TransactionID uniquely identifies a transaction

func (TransactionID) MarshalJSON added in v1.0.0

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

MarshalJSON marshals an id as a hex string.

func (TransactionID) String added in v1.0.0

func (tid TransactionID) String() string

String prints the id in hex.

func (*TransactionID) UnmarshalJSON added in v1.0.0

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

func (TransactionSignature) MarshalSia added in v1.2.0

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

MarshalSia implements the encoding.SiaMarshaler interface.

func (*TransactionSignature) UnmarshalSia added in v1.3.1

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 GenerateDeterministicMultisig added in v1.5.7

func GenerateDeterministicMultisig(m, n int, salt string) (UnlockConditions, []crypto.SecretKey)

GenerateDeterministicMultisig is a helper function that generates a set of multisig UnlockConditions along with their signing keys.

func (UnlockConditions) MarshalSia added in v1.2.0

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

MarshalSia implements the encoding.SiaMarshaler interface.

func (UnlockConditions) MarshalSiaSize added in v1.3.0

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 added in v1.3.1

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 MustParseAddress added in v1.4.0

func MustParseAddress(addrStr string) (addr UnlockHash)

MustParseAddress parses an address string to an UnlockHash, panicking if parsing fails.

MustParseAddress should never be called on untrusted input; it is provided only for convenience when working with address strings that are known to be valid, such as the addresses in GenesisSiafundAllocation. To parse untrusted address strings, use the LoadString method of UnlockHash.

func (*UnlockHash) LoadString added in v1.0.0

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 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) Scan added in v1.3.3

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 added in v1.0.0

func (uh UnlockHash) String() string

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

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.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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