modules

package
v0.4.0-beta Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2023 License: MIT Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// SeverityUnknown is the value of an uninitialized severity and should never
	// be used.
	SeverityUnknown = iota
	// SeverityInfo shows the user potentially useful information, such as the
	// status of long running actions.
	SeverityInfo
	// SeverityWarning warns the user about potential issues which might require
	// preventive actions.
	SeverityWarning
	// SeverityError should be used for information about the system where
	// immediate action is recommended to avoid further issues like loss of data.
	SeverityError
	// SeverityCritical should be used for critical errors. e.g. a lack of funds
	// causing data to get lost without immediate action.
	SeverityCritical
)

The following consts are the different types of severity levels available in the alert system.

View Source
const (

	// AlertIDWalletLockedDuringMaintenance is the id of the alert that is
	// registered if the wallet is locked during a contract renewal or formation.
	AlertIDWalletLockedDuringMaintenance = "wallet-locked"
	// AlertIDRenterAllowanceLowFunds is the id of the alert that is registered
	// if at least one contract failed to renew/form due to low allowance.
	AlertIDRenterAllowanceLowFunds = "low-funds"
	// AlertIDRenterContractRenewalError is the id of the alert that is
	// registered if at least once contract renewal or refresh failed.
	AlertIDRenterContractRenewalError = "contract-renewal-error"
	// AlertIDGatewayOffline is the id of the alert that is registered upon a
	// call to 'gateway.Offline' if the value returned is 'false' and
	// unregistered when it returns 'true'.
	AlertIDGatewayOffline = "gateway-offline"
)

The following consts are a list of AlertIDs. All IDs used throughout Satellite should be unique and listed here.

View Source
const (
	// BlocksPerHour is the number of blocks expected to be mined per hour.
	BlocksPerHour = uint64(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
)
View Source
const (
	// InitialCoinbase is the coinbase reward of the Genesis block.
	InitialCoinbase = uint64(300e3)

	// The minimum coinbase is set to 30,000. Because the coinbase
	// decreases by 1 every time, it means that Sia's coinbase will have an
	// increasingly potent dropoff for about 5 years, until inflation more
	// or less permanently settles around 2%.
	MinimumCoinbase = 30e3

	// SiafundCount is the total number of Siafunds.
	SiafundCount = 10000
)
View Source
const (
	// AcceptResponse is the response given to an RPC call to indicate
	// acceptance, i.e. that the sender wishes to continue communication.
	AcceptResponse = "accept"

	// StopResponse is the response given to an RPC call to indicate graceful
	// termination, i.e. that the sender wishes to cease communication, but
	// not due to an error.
	StopResponse = "stop"
)
View Source
const (
	// BlockSizeLimit is the maximum size of a binary-encoded Block
	// that is permitted by the consensus rules.
	BlockSizeLimit = uint64(2e6)

	// A block time of 1 block per 10 minutes is chosen to follow Bitcoin's
	// example. The security lost by lowering the block time is not
	// insignificant, and the convenience gained by lowering the blocktime
	// even down to 90 seconds is not significant. 10 minutes could even be
	// too short, but it has worked well for Bitcoin.
	BlockFrequency = 600

	// When the difficulty is adjusted, it is adjusted by looking at the
	// timestamp of the 1000th previous block. This minimizes the abilities
	// of miners to attack the network using rogue timestamps.
	TargetWindow = 1e3

	// ASICHardforkHeight is the height at which the hardfork targeting
	// selected ASICs was activated.
	ASICHardforkHeight = uint64(179000)

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

	// A total time of 120,000 is chosen because that represents the total
	// time elapsed at a perfect equilibrium, indicating a visible average
	// block time that perfectly aligns with what is expected.
	ASICHardforkTotalTime = 120e3

	// DevAddrHardforkHeight is the height at which the DevAddr hardfork was
	// activated.
	DevAddrHardforkHeight = uint64(10000)

	// The oak difficulty adjustment hardfork is set to trigger at block
	// 135,000, which is just under 6 months after the hardfork was first
	// released as beta software to the network. This hopefully gives
	// everyone plenty of time to upgrade and adopt the hardfork, while also
	// being earlier than the most optimistic shipping dates for the miners
	// that would otherwise be very disruptive to the network.
	//
	// There was a bug in the original Oak hardfork that had to be quickly
	// followed up with another fix. The height of that fix is the
	// OakHardforkFixBlock.
	OakHardforkBlock    = 135e3
	OakHardforkFixBlock = 139e3

	// OakHardforkTxnSizeLimit is the maximum size allowed for a transaction,
	// a change which was implemented simultaneously with the oak hardfork.
	OakHardforkTxnSizeLimit = uint64(64e3) // 64 KB

	// The decay is kept at 995/1000, or a decay of about 0.5% each block.
	// This puts the halflife of a block's relevance at about 1 day. This
	// allows the difficulty to adjust rapidly if the hashrate is adjusting
	// rapidly, while still keeping a relatively strong insulation against
	// random variance.
	OakDecayNum   = 995
	OakDecayDenom = 1e3

	// The block shift determines the most that the difficulty adjustment
	// algorithm is allowed to shift the target block time. With a block
	// frequency of 600 seconds, the min target block time is 200 seconds,
	// and the max target block time is 1800 seconds.
	OakMaxBlockShift = 3

	// TaxHardforkHeight is the height at which the tax hardfork occurred.
	TaxHardforkHeight = uint64(21000)

	// FoundationHardforkHeight is the height at which the Foundation subsidy
	// hardfork was activated.
	FoundationHardforkHeight = uint64(298000)

	// The Foundation subsidy hardfork activates at approximately 11pm EST
	// on February 3, 2021.
	// Subsidies are paid out approximately once per month. Since actual
	// months vary in length, we instead divide the total number of blocks
	// per year by 12.
	FoundationSubsidyFrequency = BlocksPerYear / 12

	// Blocks will not be accepted if their timestamp is more than 3 hours
	// into the future, but will be accepted as soon as they are no longer
	// 3 hours into the future. Blocks that are greater than 5 hours into
	// the future are rejected outright, as it is assumed that by the time
	// 2 hours have passed, those blocks will no longer be on the longest
	// chain. Blocks cannot be kept forever because this opens a DoS vector.
	FutureThreshold        = 3 * 60 * 60 // 3 hours.
	ExtremeFutureThreshold = 5 * 60 * 60 // 5 hours.

	// Payouts take 1 day to mature. This is to prevent a class of double
	// spending attacks where parties unintentionally spend coins that will
	// stop existing after a blockchain reorganization. There are multiple
	// classes of payouts in Sia that depend on a previous block - if that
	// block changes, then the output changes and the previously existing
	// output ceases to exist. This delay stops both unintentional double
	// spending and a small set of long-range mining attacks.
	MaturityDelay = 144

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

	// StorageProofHardforkHeight is the height at which the storage proof
	// hardfork was activated.
	StorageProofHardforkHeight = uint64(100000)
)
View Source
const (
	// TransactionSetSizeLimit defines the largest set of dependent unconfirmed
	// transactions that will be accepted by the transaction pool.
	TransactionSetSizeLimit = 250e3

	// TransactionSizeLimit defines the size of the largest transaction that
	// will be accepted by the transaction pool according to the IsStandard
	// rules.
	TransactionSizeLimit = 32e3
)
View Source
const BytesPerTerabyte = 1024 * 1024 * 1024 * 1024

BytesPerTerabyte is how many bytes are there in one TiB.

View Source
const EstimatedFileContractTransactionSetSize = 2048

EstimatedFileContractTransactionSetSize is the estimated blockchain size of a transaction set between a renter and a host that contains a file contract. This transaction set will contain a setup transaction from each the host and the renter, and will also contain a file contract and file contract revision that have each been signed by all parties.

View Source
const MaxEncodedNetAddressLength = 266

MaxEncodedNetAddressLength is the maximum length of a NetAddress encoded with the encode package. 266 was chosen because the maximum length for the hostname is 254 + 1 for the separating colon + 5 for the port + 8 byte string length prefix.

View Source
const MinMessageSize = 4096

MinMessageSize is the minimum size of an RPC message. If an encoded message would be smaller than minMessageSize, the sender MAY pad it with random data. This hinders traffic analysis by obscuring the true sizes of messages.

View Source
const (
	// PublicKeysPerSeed define the number of public keys that get pregenerated
	// for a seed at startup when searching for balances in the blockchain.
	PublicKeysPerSeed = 2500
)
View Source
const SectorSize = uint64(1 << 22)

SectorSize defines how large a sector should be in bytes. The sector size needs to be a power of two to be compatible with package merkletree. 4MiB has been chosen for the live network because large sectors significantly reduce the tracking overhead experienced by the renter and the host.

View Source
const (
	// SegmentSize is the chunk size that is used when taking the Merkle root
	// of a file. 64 is chosen because bandwidth is scarce and it optimizes for
	// the smallest possible storage proofs. Using a larger base, even 256
	// bytes, would result in substantially faster hashing, but the bandwidth
	// tradeoff was deemed to be more important, as blockchain space is scarce.
	SegmentSize = 64
)

Variables

View Source
var (
	// ConsensusChangeBeginning is a special consensus change id that tells the
	// consensus set to provide all consensus changes starting from the very
	// first diff, which includes the genesis block diff.
	ConsensusChangeBeginning = ConsensusChangeID{}

	// ConsensusChangeRecent is a special consensus change id that tells the
	// consensus set to provide the most recent consensus change, instead of
	// starting from a specific value (which may not be known to the caller).
	ConsensusChangeRecent = ConsensusChangeID{1}

	// ErrBlockKnown is an error indicating that a block is already in the
	// database.
	ErrBlockKnown = errors.New("block already present in database")

	// ErrBlockUnsolved indicates that a block did not meet the required POW
	// target.
	ErrBlockUnsolved = errors.New("block does not meet target")

	// ErrInvalidConsensusChangeID indicates that ConsensusSetPersistSubscribe
	// was called with a consensus change id that is not recognized. Most
	// commonly, this means that the consensus set was deleted or replaced and
	// now the module attempting the subscription has desynchronized. This error
	// should be handled by the module, and not reported to the user.
	ErrInvalidConsensusChangeID = errors.New("consensus subscription has invalid id - files are inconsistent")

	// ErrNonExtendingBlock indicates that a block is valid but does not result
	// in a fork that is the heaviest known fork - the consensus set has not
	// changed as a result of seeing the block.
	ErrNonExtendingBlock = errors.New("block does not extend the longest fork")
)
View Source
var (
	GenesisSiacoinAllocation = []types.SiacoinOutput{}

	GenesisSiafundAllocation = []types.SiafundOutput{
		{
			Value:   2,
			Address: types.Address{4, 57, 229, 188, 127, 20, 204, 245, 211, 167, 232, 130, 208, 64, 146, 62, 69, 98, 81, 102, 221, 7, 123, 100, 70, 107, 199, 113, 121, 26, 198, 252},
		},
		{
			Value:   6,
			Address: types.Address{4, 158, 29, 42, 105, 119, 43, 5, 138, 72, 190, 190, 101, 114, 79, 243, 189, 248, 208, 151, 30, 187, 233, 148, 225, 233, 28, 159, 19, 232, 75, 244},
		},
		{
			Value:   7,
			Address: types.Address{8, 7, 66, 250, 25, 74, 247, 108, 162, 79, 220, 151, 202, 228, 241, 11, 130, 138, 13, 248, 193, 167, 136, 197, 65, 63, 234, 174, 205, 216, 71, 230},
		},
		{
			Value:   8,
			Address: types.Address{44, 106, 239, 51, 138, 102, 242, 19, 204, 197, 248, 178, 219, 122, 152, 251, 19, 20, 52, 32, 175, 32, 4, 156, 73, 33, 163, 165, 222, 184, 217, 218},
		},
		{
			Value:   3,
			Address: types.Address{44, 163, 31, 233, 74, 103, 55, 132, 230, 159, 97, 78, 149, 147, 65, 110, 164, 211, 105, 173, 158, 29, 202, 43, 85, 217, 85, 75, 83, 37, 205, 223},
		},
		{
			Value:   1,
			Address: types.Address{51, 151, 146, 84, 199, 7, 59, 89, 111, 172, 227, 200, 62, 55, 165, 253, 238, 186, 28, 145, 47, 137, 200, 15, 70, 199, 187, 125, 243, 104, 179, 240},
		},
		{
			Value:   10,
			Address: types.Address{53, 118, 253, 229, 254, 229, 28, 131, 233, 156, 108, 58, 197, 152, 17, 160, 74, 252, 11, 49, 112, 240, 66, 119, 40, 98, 114, 251, 5, 86, 233, 117},
		},
		{
			Value:   50,
			Address: types.Address{56, 219, 3, 50, 28, 3, 166, 95, 141, 163, 202, 35, 60, 199, 219, 10, 151, 176, 228, 97, 176, 133, 189, 33, 211, 202, 83, 197, 31, 208, 254, 193},
		},
		{
			Value:   75,
			Address: types.Address{68, 190, 140, 87, 96, 232, 150, 32, 161, 177, 204, 65, 228, 223, 87, 217, 134, 90, 25, 56, 51, 45, 72, 107, 129, 12, 29, 202, 6, 7, 50, 13},
		},
		{
			Value:   10,
			Address: types.Address{69, 14, 201, 200, 90, 73, 245, 45, 154, 94, 161, 19, 199, 241, 203, 56, 13, 63, 5, 220, 121, 245, 247, 52, 194, 181, 252, 76, 130, 6, 114, 36},
		},
		{
			Value:   10,
			Address: types.Address{72, 128, 253, 207, 169, 48, 1, 26, 237, 205, 169, 102, 196, 224, 42, 186, 95, 151, 59, 226, 203, 136, 251, 223, 165, 38, 88, 110, 47, 213, 121, 224},
		},
		{
			Value:   50,
			Address: types.Address{72, 130, 164, 227, 218, 28, 60, 15, 56, 151, 212, 242, 77, 131, 232, 131, 42, 57, 132, 173, 113, 118, 66, 183, 38, 79, 96, 178, 105, 108, 26, 247},
		},
		{
			Value:   10,
			Address: types.Address{74, 210, 58, 228, 111, 69, 253, 120, 53, 195, 110, 26, 115, 76, 211, 202, 199, 159, 204, 14, 78, 92, 14, 131, 250, 22, 141, 236, 154, 44, 39, 135},
		},
		{
			Value:   15,
			Address: types.Address{85, 198, 154, 41, 196, 116, 226, 114, 202, 94, 214, 147, 87, 84, 247, 164, 195, 79, 58, 123, 26, 33, 68, 65, 116, 79, 181, 241, 241, 208, 215, 184},
		},
		{
			Value:   121,
			Address: types.Address{87, 239, 83, 125, 152, 14, 19, 22, 203, 136, 46, 192, 203, 87, 224, 190, 77, 236, 125, 18, 142, 223, 146, 70, 16, 23, 252, 19, 100, 69, 91, 111},
		},
		{
			Value:   222,
			Address: types.Address{91, 201, 101, 11, 188, 40, 35, 111, 236, 133, 31, 124, 97, 246, 140, 136, 143, 245, 152, 174, 111, 245, 188, 124, 21, 125, 187, 192, 203, 92, 253, 57},
		},
		{
			Value:   10,
			Address: types.Address{110, 240, 238, 173, 78, 138, 185, 138, 179, 227, 135, 153, 54, 132, 46, 62, 226, 206, 204, 35, 174, 107, 156, 15, 142, 2, 93, 132, 163, 60, 50, 89},
		},
		{
			Value:   3,
			Address: types.Address{114, 58, 147, 44, 64, 69, 72, 184, 65, 178, 213, 94, 157, 44, 88, 106, 92, 31, 145, 193, 215, 200, 215, 233, 99, 116, 36, 197, 160, 70, 79, 153},
		},
		{
			Value:   1,
			Address: types.Address{123, 106, 229, 101, 220, 252, 50, 203, 38, 183, 133, 152, 250, 167, 210, 155, 252, 102, 150, 29, 187, 3, 178, 53, 11, 145, 143, 33, 166, 115, 250, 40},
		},
		{
			Value:   5,
			Address: types.Address{124, 101, 207, 175, 50, 119, 207, 26, 62, 15, 247, 141, 150, 174, 73, 247, 238, 28, 77, 255, 222, 104, 166, 244, 112, 86, 227, 80, 215, 45, 69, 143},
		},
		{
			Value:   10,
			Address: types.Address{130, 184, 72, 15, 227, 79, 217, 205, 120, 254, 67, 69, 10, 49, 76, 194, 222, 30, 242, 62, 88, 179, 51, 117, 27, 166, 140, 6, 7, 22, 222, 185},
		},
		{
			Value:   25,
			Address: types.Address{134, 137, 198, 172, 96, 54, 45, 10, 100, 128, 91, 225, 226, 134, 143, 108, 31, 70, 187, 228, 54, 212, 70, 229, 149, 57, 64, 166, 153, 123, 238, 180},
		},
		{
			Value:   1,
			Address: types.Address{143, 253, 118, 229, 109, 181, 141, 224, 91, 144, 123, 160, 203, 221, 119, 104, 172, 13, 105, 77, 171, 185, 122, 54, 229, 168, 6, 130, 160, 130, 182, 151},
		},
		{
			Value:   8,
			Address: types.Address{147, 108, 249, 16, 36, 249, 108, 184, 196, 212, 241, 120, 219, 63, 45, 184, 86, 53, 96, 207, 130, 96, 210, 251, 136, 9, 193, 160, 131, 198, 221, 185},
		},
		{
			Value:   58,
			Address: types.Address{155, 79, 89, 28, 69, 71, 239, 198, 246, 2, 198, 254, 92, 59, 192, 205, 229, 152, 36, 186, 110, 122, 233, 221, 76, 143, 3, 238, 89, 231, 192, 23},
		},
		{
			Value:   2,
			Address: types.Address{156, 32, 76, 105, 213, 46, 66, 50, 27, 85, 56, 9, 106, 193, 80, 145, 19, 101, 84, 177, 145, 4, 125, 28, 79, 252, 43, 83, 118, 110, 206, 247},
		},
		{
			Value:   23,
			Address: types.Address{157, 169, 134, 24, 254, 22, 58, 188, 119, 87, 201, 238, 55, 168, 194, 131, 88, 18, 39, 168, 37, 2, 198, 194, 93, 202, 116, 146, 189, 17, 108, 44},
		},
		{
			Value:   10,
			Address: types.Address{158, 51, 104, 36, 242, 114, 67, 16, 168, 230, 4, 111, 241, 72, 5, 14, 182, 102, 169, 156, 144, 220, 103, 117, 223, 8, 58, 187, 124, 102, 80, 44},
		},
		{
			Value:   1,
			Address: types.Address{160, 175, 59, 33, 223, 30, 82, 60, 34, 110, 28, 203, 249, 93, 3, 16, 218, 12, 250, 206, 138, 231, 85, 67, 69, 191, 68, 198, 160, 87, 154, 68},
		},
		{
			Value:   75,
			Address: types.Address{163, 94, 51, 220, 14, 144, 83, 112, 62, 10, 0, 173, 161, 234, 211, 176, 186, 84, 9, 189, 250, 111, 33, 231, 114, 87, 100, 75, 72, 217, 11, 26},
		},
		{
			Value:   3,
			Address: types.Address{170, 7, 138, 116, 205, 20, 132, 197, 166, 251, 75, 93, 69, 6, 109, 244, 212, 119, 173, 114, 34, 18, 25, 21, 111, 203, 203, 253, 138, 104, 27, 36},
		},
		{
			Value:   90,
			Address: types.Address{173, 120, 128, 104, 186, 86, 151, 140, 191, 23, 231, 193, 77, 245, 243, 104, 196, 55, 155, 243, 111, 15, 84, 139, 148, 187, 173, 47, 104, 69, 141, 39},
		},
		{
			Value:   20,
			Address: types.Address{179, 185, 228, 166, 139, 94, 13, 193, 255, 227, 174, 99, 120, 105, 109, 221, 247, 4, 155, 243, 229, 37, 26, 98, 222, 12, 91, 80, 223, 33, 61, 56},
		},
		{
			Value:   5,
			Address: types.Address{193, 49, 103, 20, 170, 135, 182, 85, 149, 18, 159, 194, 152, 120, 162, 208, 49, 158, 220, 188, 114, 79, 1, 131, 62, 27, 86, 57, 244, 46, 64, 66},
		},
		{
			Value:   1,
			Address: types.Address{196, 71, 45, 222, 0, 21, 12, 121, 197, 224, 101, 65, 40, 57, 19, 119, 112, 205, 166, 23, 2, 91, 75, 231, 69, 143, 221, 68, 245, 75, 7, 52},
		},
		{
			Value:   44,
			Address: types.Address{196, 214, 236, 211, 227, 216, 152, 127, 164, 2, 235, 14, 235, 46, 142, 231, 83, 38, 7, 131, 208, 29, 179, 189, 62, 88, 129, 180, 119, 158, 214, 97},
		},
		{
			Value:   23,
			Address: types.Address{206, 58, 114, 148, 131, 49, 87, 197, 86, 18, 216, 26, 62, 79, 152, 175, 33, 4, 132, 160, 108, 231, 53, 200, 48, 76, 125, 94, 156, 85, 32, 130},
		},
		{
			Value:   80,
			Address: types.Address{200, 103, 135, 126, 197, 2, 203, 63, 241, 6, 245, 195, 220, 102, 27, 74, 232, 249, 201, 86, 207, 34, 51, 26, 180, 151, 136, 108, 112, 56, 132, 72},
		},
		{
			Value:   2,
			Address: types.Address{200, 249, 245, 218, 58, 253, 76, 250, 88, 114, 70, 239, 14, 2, 250, 123, 10, 192, 198, 61, 187, 155, 247, 152, 165, 174, 198, 24, 142, 39, 177, 119},
		},
		{
			Value:   1,
			Address: types.Address{209, 1, 199, 184, 186, 57, 21, 137, 33, 252, 219, 184, 130, 38, 32, 98, 63, 252, 250, 79, 70, 146, 169, 78, 180, 161, 29, 93, 38, 45, 175, 176},
		},
		{
			Value:   2,
			Address: types.Address{212, 107, 233, 43, 185, 138, 79, 253, 12, 237, 214, 17, 219, 198, 151, 92, 81, 129, 17, 120, 139, 58, 66, 119, 126, 220, 132, 136, 3, 108, 57, 58},
		},
		{
			Value:   3,
			Address: types.Address{214, 244, 146, 173, 173, 80, 33, 185, 29, 133, 77, 167, 185, 1, 38, 23, 111, 179, 104, 150, 105, 162, 120, 26, 245, 63, 114, 119, 52, 1, 44, 222},
		},
		{
			Value:   1,
			Address: types.Address{217, 218, 172, 16, 53, 134, 160, 226, 44, 138, 93, 53, 181, 62, 4, 209, 190, 27, 0, 93, 105, 17, 169, 61, 98, 145, 131, 112, 121, 55, 97, 184},
		},
		{
			Value:   1,
			Address: types.Address{223, 162, 172, 55, 54, 193, 37, 142, 200, 213, 230, 48, 186, 145, 184, 206, 15, 225, 167, 19, 37, 70, 38, 48, 135, 87, 205, 81, 187, 237, 181, 180},
		},
		{
			Value:   1,
			Address: types.Address{241, 46, 139, 41, 40, 63, 47, 169, 131, 173, 124, 246, 228, 213, 102, 44, 100, 217, 62, 237, 133, 154, 248, 69, 228, 2, 36, 206, 47, 250, 249, 170},
		},
		{
			Value:   50,
			Address: types.Address{241, 50, 229, 211, 66, 32, 115, 241, 117, 87, 180, 239, 76, 246, 14, 129, 105, 181, 153, 105, 105, 203, 229, 237, 23, 130, 193, 170, 100, 201, 38, 71},
		},
		{
			Value:   8841,
			Address: types.Address{125, 12, 68, 247, 102, 78, 45, 52, 229, 62, 253, 224, 102, 26, 111, 98, 142, 201, 38, 71, 133, 174, 142, 60, 215, 201, 115, 232, 209, 144, 195, 201},
		},
	}

	// The genesis timestamp is set to June 6th, because that is when the
	// 100-block developer premine started. The trailing zeroes are a
	// bonus, and make the timestamp easier to memorize.
	GenesisTimestamp = time.Unix(1433600000, 0) // June 6th, 2015 @ 2:13pm UTC.

	// GenesisBlock is the first block of the block chain.
	GenesisBlock = types.Block{
		Timestamp: GenesisTimestamp,
		Transactions: []types.Transaction{
			{
				SiacoinOutputs: GenesisSiacoinAllocation,
				SiafundOutputs: GenesisSiafundAllocation,
			},
		},
	}

	// GenesisID is used in many places. Calculating it once saves lots of
	// redundant computation.
	GenesisID = GenesisBlock.ID()

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

	// The RootTarget was set such that the developers could reasonable
	// premine 100 blocks in a day. It was known to the developers at launch
	// this this was at least one and perhaps two orders of magnitude too
	// small.
	RootTarget = Target{0, 0, 0, 0, 32}

	// The difficulty adjustment is clamped to 2.5x every 500 blocks. This
	// corresponds to 6.25x every 2 weeks, which can be compared to
	// Bitcoin's clamp of 4x every 2 weeks. The difficulty clamp is
	// primarily to stop difficulty raising attacks. Sia's safety margin is
	// similar to Bitcoin's despite the looser clamp because Sia's
	// difficulty is adjusted four times as often. This does result in
	// greater difficulty oscillation, a tradeoff that was chosen to be
	// acceptable due to Sia's more vulnerable position as an altcoin.
	MaxTargetAdjustmentUp   = big.NewRat(25, 10)
	MaxTargetAdjustmentDown = big.NewRat(10, 25)

	// A total target of 67 leading zeroes is chosen because that aligns
	// with the amount of hashrate that we expect to be on the network
	// after the hardfork.
	ASICHardforkTotalTarget = Target{0, 0, 0, 0, 0, 0, 0, 0, 32}

	// The max rise and max drop for the difficulty is kept at 0.4% per
	// block, which means that in 1008 blocks the difficulty can move a
	// maximum of about 55x. This is significant, and means that dramatic
	// hashrate changes can be responded to quickly, while still forcing an
	// attacker to do a significant amount of work in order to execute a
	// difficulty raising attack, and minimizing the chance that an attacker
	// can get lucky and fake a ton of work.
	OakMaxRise = big.NewRat(1004, 1e3)
	OakMaxDrop = big.NewRat(1e3, 1004)

	// 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 = types.HastingsPerSiacoin.Mul64(30e3).Mul64(BlocksPerYear)

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

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

	// 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 types.Address

	// 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 types.Address
)
View Source
var (
	// FormContractFee is how much the satellite charges for
	// forming or renewing a single contract.
	FormContractFee = 0.1 // 10% of the contract amount

	// SaveMetadataFee is the fee for saving a single slab
	// metadata.
	SaveMetadataFee = 0.1 // 100 mS / slab

	// StoreMetadataFee is the fee for storing a single slab
	// metadata for one month.
	StoreMetadataFee = 1 // 1 SC/slab/month

	// RetrieveMetadataFee is the fee for retrieving a single
	// slab metadata.
	RetrieveMetadataFee = 0.1 // 100 mS/slab

	// MigrateSlabFee is the fee for migrating a single slab.
	MigrateSlabFee = 0.01 // 10 mS/slab
)
View Source
var (
	// MaxRPCPrice is how much the Satellite is willing to pay
	// for a single RPC call.
	MaxRPCPrice = types.HastingsPerSiacoin.Div64(1e6)

	// MaxSectorAccessPrice is how much the Satellite is willing
	// to pay to download a single sector.
	MaxSectorAccessPrice = types.HastingsPerSiacoin.Div64(1e5)
)
View Source
var (
	// ErrDuplicateTransactionSet is the error that gets returned if a
	// duplicate transaction set is given to the transaction pool.
	ErrDuplicateTransactionSet = errors.New("transaction set contains only duplicate transactions")

	// ErrInvalidArbPrefix is the error that gets returned if a transaction is
	// submitted to the transaction pool which contains a prefix that is not
	// recognized. This helps prevent miners on old versions from mining
	// potentially illegal transactions in the event of a soft-fork.
	ErrInvalidArbPrefix = errors.New("transaction contains non-standard arbitrary data")

	// ErrLargeTransaction is the error that gets returned if a transaction
	// provided to the transaction pool is larger than what is allowed by the
	// IsStandard rules.
	ErrLargeTransaction = errors.New("transaction is too large for this transaction pool")

	// ErrLargeTransactionSet is the error that gets returned if a transaction
	// set given to the transaction pool is larger than the limit placed by the
	// IsStandard rules of the transaction pool.
	ErrLargeTransactionSet = errors.New("transaction set is too large for this transaction pool")

	// PrefixNonSia defines the prefix that should be appended to any
	// transactions that use the arbitrary data for reasons outside of the
	// standard Sia protocol. This will prevent these transactions from being
	// rejected by the IsStandard set of rules, but also means that the data
	// will never be used within the formal Sia protocol.
	PrefixNonSia = types.NewSpecifier("NonSia")

	// PrefixHostAnnouncement is used to indicate that a transaction's
	// Arbitrary Data field contains a host announcement. The encoded
	// announcement will follow this prefix.
	PrefixHostAnnouncement = types.NewSpecifier("HostAnnouncement")

	// PrefixFileContractIdentifier is used to indicate that a transaction's
	// Arbitrary Data field contains a file contract identifier. The identifier
	// and its signature will follow this prefix.
	PrefixFileContractIdentifier = types.NewSpecifier("FCIdentifier")
)
View Source
var (
	// ErrInvalidSignature is returned if a signature is provided that does not
	// match the data and public key.
	ErrInvalidSignature = errors.New("invalid signature")
	// 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")
	// 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")

	// SignatureEd25519 is a specifier for Ed22519
	SignatureEd25519 = types.NewSpecifier("ed25519")
	// SignatureEntropy is a specifier for entropy
	SignatureEntropy = types.NewSpecifier("entropy")
)
View Source
var (
	// ErrBadEncryptionKey is returned if the incorrect encryption key to a
	// file is provided.
	ErrBadEncryptionKey = errors.New("provided encryption key is incorrect")

	// ErrIncompleteTransactions is returned if the wallet has incomplete
	// transactions being built that are using all of the current outputs, and
	// therefore the wallet is unable to spend money despite it not technically
	// being 'unconfirmed' yet.
	ErrIncompleteTransactions = errors.New("wallet has coins spent in incomplete transactions - not enough remaining coins")

	// ErrLockedWallet is returned when an action cannot be performed due to
	// the wallet being locked.
	ErrLockedWallet = errors.New("wallet must be unlocked before it can be used")

	// ErrLowBalance is returned if the wallet does not have enough funds to
	// complete the desired action.
	ErrLowBalance = errors.New("insufficient balance")

	// ErrWalletShutdown is returned when a method can't continue execution due
	// to the wallet shutting down.
	ErrWalletShutdown = errors.New("wallet is shutting down")
)
View Source
var (
	// BlockBytesPerMonthTerabyte is the conversion rate between block-bytes and month-TB.
	BlockBytesPerMonthTerabyte = types.NewCurrency64(BytesPerTerabyte).Mul64(BlocksPerMonth)
)
View Source
var (
	// BootstrapPeers is a list of peers that can be used to find other peers -
	// when a client first connects to the network, the only options for
	// finding peers are either manual entry of peers or to use a hardcoded
	// bootstrap point. While the bootstrap point could be a central service,
	// it can also be a list of peers that are known to be stable. We have
	// chosen to hardcode known-stable peers.
	//
	// These peers have been verified to be v1.5.4 or higher.
	BootstrapPeers = []NetAddress{
		"82.65.206.23:9981",
		"135.181.208.120:9981",
		"176.106.59.120:9981",
		"144.91.127.102:9981",
		"109.195.83.186:9981",
		"96.60.27.112:5151",
		"144.217.7.188:9981",
		"5.9.19.246:9981",
		"94.110.4.134:9981",
		"208.88.8.166:5151",
		"139.162.81.190:9981",
		"5.19.177.22:9981",
		"13.113.190.118:9981",
		"134.209.89.131:9981",
		"176.104.8.173:9981",
		"81.25.225.178:9981",
		"147.135.23.200:9981",
		"76.216.70.162:9981",
		"72.8.228.138:9981",
		"164.138.31.105:9981",
		"78.69.28.182:9861",
		"176.215.255.127:9981",
		"72.69.188.134:9981",
		"71.237.62.44:9981",
		"95.211.140.149:9981",
		"5.196.66.75:9981",
		"2.26.62.61:9981",
		"88.98.208.124:9981",
		"50.116.14.37:9981",
		"173.235.144.230:9981",
		"73.74.104.175:10031",
		"199.195.252.152:9981",
		"135.181.142.113:9981",
		"148.251.152.35:9981",
		"148.251.125.117:9981",
		"136.52.87.46:9981",
		"82.217.213.145:9981",
		"81.7.16.159:9681",
		"146.52.104.39:9981",
		"78.197.237.216:9981",
		"162.196.91.121:9981",
		"148.251.82.174:9981",
		"65.21.79.100:9981",
		"103.76.41.143:9981",
		"81.98.132.81:9981",
		"109.236.92.161:9981",
		"167.86.109.162:9981",
		"139.162.187.240:9991",
		"92.83.254.237:9791",
		"80.101.32.17:9981",
		"81.196.138.172:11152",
		"50.54.136.187:9981",
		"5.39.76.82:9981",
		"92.90.91.29:9981",
		"116.202.87.160:9981",
		"13.212.22.103:9981",
		"5.141.81.96:9981",
		"66.176.169.2:9981",
		"92.58.23.92:9981",
		"149.248.110.111:9981",
		"142.182.59.54:9981",
		"190.111.196.118:9981",
		"54.38.120.222:9981",
		"109.195.166.133:9981",
		"172.104.15.208:9981",
		"65.30.133.139:9981",
		"95.217.180.130:9981",
		"82.223.202.234:9981",
		"82.64.236.171:9981",
		"188.122.0.242:9991",
		"121.41.105.53:9981",
		"161.97.176.97:9981",
		"71.178.248.177:9981",
		"89.69.17.157:9981",
		"63.141.234.114:9981",
	}
)
View Source
var DefaultAllowance = Allowance{
	Funds:       types.HastingsPerSiacoin.Mul64(2500),
	Hosts:       50,
	Period:      2 * BlocksPerMonth,
	RenewWindow: BlocksPerMonth,

	ExpectedStorage:   1e12,
	ExpectedUpload:    uint64(200e9) / BlocksPerMonth,
	ExpectedDownload:  uint64(100e9) / BlocksPerMonth,
	MinShards:         10,
	TotalShards:       30,
	BlockHeightLeeway: 3,
}

DefaultAllowance is the set of default allowance settings that will be used when allowances are not set or not fully set.

View Source
var ErrInsufficientLen = errors.New("supplied ciphertext is not long enough to contain a nonce")

ErrInsufficientLen is an error when supplied ciphertext is not long enough to contain a nonce.

Functions

func AddContext

func AddContext(err error, ctx string) error

AddContext wraps an error in a context.

func CalculateCoinbase

func CalculateCoinbase(height uint64) types.Currency

CalculateCoinbase calculates the coinbase for a given height. The coinbase equation is: coinbase := max(InitialCoinbase - height, MinimumCoinbase)

func CalculateFee

func CalculateFee(ts []types.Transaction) types.Currency

CalculateFee returns the fee-per-byte of a transaction set.

func CalculateLeaves

func CalculateLeaves(dataSize uint64) uint64

CalculateLeaves calculates the number of leaves that would be pushed from data of size 'dataSize'.

func CalculateNumSiacoins

func CalculateNumSiacoins(height uint64) (total types.Currency)

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

func CalculateSubsidy

func CalculateSubsidy(b types.Block, height uint64) types.Currency

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

func CheckGouging

func CheckGouging(a Allowance, height uint64, hs *rhpv2.HostSettings, pt *rhpv3.HostPriceTable, txnFee types.Currency) (err error)

CheckGouging performs a number of gouging checks before forming a contract with the host.

func ComposeErrors

func ComposeErrors(errs ...error) error

ComposeErrors combines several errors in one.

func ContainsError

func ContainsError(base, target error) bool

ContainsError checks if one error contains the other.

func CopyTransaction

func CopyTransaction(txn types.Transaction) types.Transaction

CopyTransaction creates a deep copy of the transaction.

func Decrypt

func Decrypt(key WalletKey, ciphertext []byte) ([]byte, error)

Decrypt decrypts the ciphertext using the provided key.

func DeriveAccountKey

func DeriveAccountKey(ak types.PrivateKey, hpk types.PublicKey) types.PrivateKey

DeriveAccountKey derives an account key to be used by the renter to access the ephemeral account at the host.

func DeriveEphemeralKey

func DeriveEphemeralKey(rsk types.PrivateKey, hpk types.PublicKey) types.PrivateKey

DeriveEphemeralKey derives a secret key to be used by the renter for the exchange with the host.

func DeriveRenterSeed

func DeriveRenterSeed(walletSeed Seed, email string) []byte

DeriveRenterSeed derives a seed to be used by the renter for accessing the file contracts. NOTE: The seed returned by this function should be wiped once it's no longer in use.

func EncodeBIP39Phrase

func EncodeBIP39Phrase(entropy Seed) string

EncodeBIP39Phrase derives a seed phrase from the entropy.

func Encrypt

func Encrypt(key WalletKey, plaintext []byte) ([]byte, error)

Encrypt encrypts the plaintext with the provided key.

func ExplicitCoveredFields

func ExplicitCoveredFields(txn types.Transaction) (cf types.CoveredFields)

ExplicitCoveredFields returns a CoveredFields that covers all elements present in txn.

func FilesizeUnits

func FilesizeUnits(size uint64) string

FilesizeUnits returns a string that displays a filesize in human-readable units.

func Float64

func Float64(c types.Currency) float64

Float64 converts types.Currency to float64.

func FromFloat

func FromFloat(f float64) types.Currency

FromFloat converts f Siacoins to a types.Currency value.

func FullCoveredFields

func FullCoveredFields() types.CoveredFields

FullCoveredFields returns a CoveredFields that covers the whole transaction.

func GenerateKeyPair

func GenerateKeyPair(seed types.Hash256) (sk types.PrivateKey, pk types.PublicKey)

GenerateKeyPair generates a private/public keypair from a seed.

func IsConsensusConflict

func IsConsensusConflict(err error) bool

IsConsensusConflict returns true if err is a ConsensusConflict.

func KeyFromPhrase

func KeyFromPhrase(phrase string) (types.PrivateKey, error)

KeyFromPhrase returns the Ed25519 key derived from the supplied seed phrase.

func MinimumTransactionSet

func MinimumTransactionSet(requiredTxns []types.Transaction, relatedTxns []types.Transaction) []types.Transaction

MinimumTransactionSet takes two transaction sets as input and returns a combined transaction set. The first input is the set of required transactions, which the caller is indicating must all be a part of the final set.The second input is a set of related transactions that the caller believes may contain parent transactions of the required transactions. MinimumCombinedSet will scan through the related transactions and pull in any which are required parents of the required transactions, returning the final result.

The final transaction set which gets returned will contain all of the required transactions, and will contain any of the related transactions which are necessary for the required transactions to be confirmed.

NOTE: Both of the inputs are proper transaction sets. A proper transaction set is already sorted so that no parent comes after a child in the array.

func MulFloat

func MulFloat(c types.Currency, f float64) types.Currency

MulFloat multiplies a types.Currency by a float64 value.

func NewSeedPhrase

func NewSeedPhrase() string

NewSeedPhrase returns a random seed phrase.

func PartialSigHash

func PartialSigHash(t types.Transaction, cf types.CoveredFields, height uint64) (hash types.Hash256)

PartialSigHash calculates the hash of the fields of the transaction specified in cf.

func PeekErr

func PeekErr(errChan <-chan error) (err error)

PeekErr checks if a chan error has an error waiting to be returned. If it has it will return that error. Otherwise it returns 'nil'.

func PostTax

func PostTax(height uint64, payout types.Currency) types.Currency

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

func PrintAlerts

func PrintAlerts(alerts []Alert, as AlertSeverity)

PrintAlerts is a helper function to print details of a slice of alerts with given severity description to command line.

func ReadBool

func ReadBool(d *types.Decoder) bool

ReadBool reads a bool from the underlying stream.

func ReadBytes

func ReadBytes(d *types.Decoder) []byte

ReadBytes reads a byte slice from the underlying stream.

func ReadCurrency

func ReadCurrency(s string) types.Currency

ReadCurrency converts a string to types.Currency.

func ReadString

func ReadString(d *types.Decoder) string

ReadString reads a string from the underlying stream.

func ReadUint64

func ReadUint64(d *types.Decoder) uint64

ReadUint64 reads an uint64 from the underlying stream.

func RenterPayoutsPreTax

func RenterPayoutsPreTax(host HostDBEntry, funding, txnFee, basePrice, baseCollateral types.Currency, period uint64, expectedStorage uint64) (renterPayout, hostPayout, hostCollateral types.Currency, err error)

RenterPayoutsPreTax calculates the renterPayout before tax and the hostPayout given a host, the available renter funding, the expected txnFee for the transaction and an optional basePrice in case this helper is used for a renewal. It also returns the hostCollateral.

func SiacoinOutputSum

func SiacoinOutputSum(t types.Transaction) (sum types.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 SigHash

func SigHash(t types.Transaction, i int, height uint64) (hash types.Hash256)

SigHash returns the hash of the fields in a transaction covered by a given signature.

func StandaloneValid

func StandaloneValid(t types.Transaction, currentHeight uint64) (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 StorageProofOutputID

func StorageProofOutputID(fcid types.FileContractID, proofStatus bool, i int) types.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 Tax

func Tax(height uint64, payout types.Currency) types.Currency

Tax calculates the Siafund fee from the amount.

func VerifyRangeProof

func VerifyRangeProof(segments []byte, proof []types.Hash256, start, end int, root types.Hash256) bool

VerifyRangeProof verifies a proof produced by MerkleRangeProof.

VerifyRangeProof for a single segment is NOT equivalent to VerifySegment.

func VerifySegment

func VerifySegment(base []byte, hashSet []types.Hash256, numSegments, proofIndex uint64, root types.Hash256) bool

VerifySegment will verify that a segment, given the proof, is a part of a Merkle root.

func WholeSigHash

func WholeSigHash(t types.Transaction, sig types.TransactionSignature, height uint64) (hash types.Hash256)

WholeSigHash calculates the hash for a signature that specifies WholeTransaction = true.

func WriteBool

func WriteBool(b bool, e *types.Encoder)

WriteBool writes a bool to the underlying stream.

func WriteBytes

func WriteBytes(b []byte, e *types.Encoder)

WriteBytes writes a byte slice to the underlying stream.

func WriteString

func WriteString(s string, e *types.Encoder)

WriteString writes a string to the underlying stream.

func WriteUint64

func WriteUint64(i uint64, e *types.Encoder)

WriteUint64 writes an uint64 to the underlying stream.

Types

type Alert

type Alert struct {
	// Cause is the cause for the Alert.
	// e.g. "Wallet is locked"
	Cause string `json:"cause"`
	// Msg is the message the Alert is meant to convey to the user.
	// e.g. "Contractor can't form new contracts".
	Msg string `json:"msg"`
	// Module contains information about what module the alert originated from.
	Module string `json:"module"`
	// Severity categorizes the Alerts to allow for an easy way to filter them.
	Severity AlertSeverity `json:"severity"`
}

Alert is a type that contains essential information about an alert.

func (Alert) Equals

func (x Alert) Equals(y Alert) bool

Equals returns true if x and y are identical alerts.

func (Alert) EqualsWithErrorCause

func (x Alert) EqualsWithErrorCause(y Alert, causeErr string) bool

EqualsWithErrorCause returns true if x and y have the same module, message, and severity and if the provided error is in both of the alert's causes.

type AlertID

type AlertID string

AlertID is a helper type for an Alert's ID.

type AlertSeverity

type AlertSeverity uint64

AlertSeverity describes the severity of an alert.

func (AlertSeverity) MarshalJSON

func (a AlertSeverity) MarshalJSON() ([]byte, error)

MarshalJSON defines a JSON encoding for the AlertSeverity.

func (AlertSeverity) String

func (a AlertSeverity) String() string

String converts an alertSeverity to a string

func (*AlertSeverity) UnmarshalJSON

func (a *AlertSeverity) UnmarshalJSON(b []byte) error

UnmarshalJSON attempts to decode an AlertSeverity.

type Alerter

type Alerter interface {
	Alerts() (crit, err, warn, info []Alert)
}

Alerter is the interface implemented by all top-level modules. It's an interface that allows for asking a module about potential issues.

type Allowance

type Allowance struct {
	Funds       types.Currency
	Hosts       uint64
	Period      uint64
	RenewWindow uint64

	// ExpectedStorage is the amount of data that we expect to have in a contract.
	ExpectedStorage uint64

	// ExpectedUpload is the expected amount of data uploaded through the API,
	// before redundancy, per block.
	ExpectedUpload uint64

	// ExpectedDownload is the expected amount of data downloaded through the
	// API per block.
	ExpectedDownload uint64

	// Erasure coding parameters.
	MinShards   uint64
	TotalShards uint64

	// The following fields provide price gouging protection for the user. By
	// setting a particular maximum price for each mechanism that a host can use
	// to charge users, the workers know to avoid hosts that go outside of the
	// safety range.
	MaxRPCPrice               types.Currency
	MaxContractPrice          types.Currency
	MaxDownloadBandwidthPrice types.Currency
	MaxSectorAccessPrice      types.Currency
	MaxStoragePrice           types.Currency
	MaxUploadBandwidthPrice   types.Currency
	MinMaxCollateral          types.Currency
	BlockHeightLeeway         uint64
}

An Allowance dictates how much the renter is allowed to spend in a given period. Note that funds are spent on both storage and bandwidth.

func (Allowance) Active

func (a Allowance) Active() bool

Active returns true if and only if this allowance has been set in the contractor.

func (*Allowance) DecodeFrom

func (a *Allowance) DecodeFrom(d *types.Decoder)

DecodeFrom implements types.DecoderFrom.

func (*Allowance) EncodeTo

func (a *Allowance) EncodeTo(e *types.Encoder)

EncodeTo implements types.EncoderTo.

type ConsensusChange

type ConsensusChange struct {
	// ID is a unique id for the consensus change derived from the reverted
	// and applied blocks.
	ID ConsensusChangeID

	// BlockHeight is the height of the chain after all blocks included in
	// this change have been reverted and applied.
	BlockHeight uint64

	// RevertedBlocks is the list of blocks that were reverted by the change.
	// The reverted blocks were always all reverted before the applied blocks
	// were applied. The revered blocks are presented in the order that they
	// were reverted.
	RevertedBlocks []types.Block

	// AppliedBlocks is the list of blocks that were applied by the change. The
	// applied blocks are always all applied after all the reverted blocks were
	// reverted. The applied blocks are presented in the order that they were
	// applied.
	AppliedBlocks []types.Block

	// RevertedDiffs is the set of diffs caused by reverted blocks. Each
	// element corresponds to a block in RevertedBlocks.
	RevertedDiffs []ConsensusChangeDiffs

	// AppliedDiffs is the set of diffs caused by applied blocks. Each
	// element corresponds to a block in AppliedBlocks.
	AppliedDiffs []ConsensusChangeDiffs

	// ConsensusChangeDiffs is the concatenation of all RevertedDiffs and
	// AppliedDiffs.
	ConsensusChangeDiffs

	// ChildTarget defines the target of any block that would be the child
	// of the block most recently appended to the consensus set.
	ChildTarget Target

	// MinimumValidChildTimestamp defines the minimum allowed timestamp for
	// any block that is the child of the block most recently appended to
	// the consensus set.
	MinimumValidChildTimestamp time.Time

	// Synced indicates whether or not the ConsensusSet is synced with its
	// peers.
	Synced bool

	// TryTransactionSet is an unlocked version of
	// ConsensusSet.TryTransactionSet. This allows the TryTransactionSet
	// function to be called by a subscriber during
	// ProcessConsensusChange.
	TryTransactionSet func([]types.Transaction) (ConsensusChange, error)
}

A ConsensusChange enumerates a set of changes that occurred to the consensus set.

func (*ConsensusChange) AppendDiffs

func (cc *ConsensusChange) AppendDiffs(diffs ConsensusChangeDiffs)

AppendDiffs appends a set of diffs to cc.

func (*ConsensusChange) DecodeFrom

func (cc *ConsensusChange) DecodeFrom(d *types.Decoder)

DecodeFrom implements types.DecoderFrom.

func (*ConsensusChange) EncodeTo

func (cc *ConsensusChange) EncodeTo(e *types.Encoder)

EncodeTo implements types.EncoderTo.

func (*ConsensusChange) InitialHeight

func (cc *ConsensusChange) InitialHeight() uint64

InitialHeight returns the height of the consensus before blocks are applied.

type ConsensusChangeDiffs

type ConsensusChangeDiffs struct {
	SiacoinOutputDiffs        []SiacoinOutputDiff
	FileContractDiffs         []FileContractDiff
	SiafundOutputDiffs        []SiafundOutputDiff
	DelayedSiacoinOutputDiffs []DelayedSiacoinOutputDiff
	SiafundPoolDiffs          []SiafundPoolDiff
}

ConsensusChangeDiffs is a collection of diffs caused by a single block. If the block was reverted, the individual diff directions are inverted. For example, a block that spends an output and creates a miner payout would have one SiacoinOutputDiff with direction DiffRevert and one DelayedSiacoinOutputDiff with direction DiffApply. If the same block were reverted, the SCOD would have direction DiffApply and the DSCOD would have direction DiffRevert.

func (*ConsensusChangeDiffs) DecodeFrom

func (ccd *ConsensusChangeDiffs) DecodeFrom(d *types.Decoder)

DecodeFrom implements types.DecoderFrom.

func (*ConsensusChangeDiffs) EncodeTo

func (ccd *ConsensusChangeDiffs) EncodeTo(e *types.Encoder)

EncodeTo implements types.EncoderTo.

type ConsensusChangeID

type ConsensusChangeID types.Hash256

ConsensusChangeID is the id of a consensus change.

func (ConsensusChangeID) String

func (ccID ConsensusChangeID) String() string

String returns the ConsensusChangeID as a string.

type ConsensusConflict

type ConsensusConflict string

ConsensusConflict implements the error interface, and indicates that a transaction was rejected due to being incompatible with the current consensus set, meaning either a double spend or a consensus rule violation - it is unlikely that the transaction will ever be valid.

func NewConsensusConflict

func NewConsensusConflict(s string) ConsensusConflict

NewConsensusConflict returns a consensus conflict, which implements the error interface.

func (ConsensusConflict) Error

func (cc ConsensusConflict) Error() string

Error implements the error interface, turning the consensus conflict into an acceptable error type.

type ConsensusSet

type ConsensusSet interface {
	Alerter

	// AcceptBlock adds a block to consensus. An error will be returned if the
	// block is invalid, has been seen before, is an orphan, or doesn't
	// contribute to the heaviest fork known to the consensus set. If the block
	// does not become the head of the heaviest known fork but is otherwise
	// valid, it will be remembered by the consensus set but an error will
	// still be returned.
	AcceptBlock(types.Block) error

	// BlockAtHeight returns the block found at the input height, with a
	// bool to indicate whether that block exists.
	BlockAtHeight(uint64) (types.Block, bool)

	// BlocksByID returns a block found for a given ID and its height, with
	// a bool to indicate whether that block exists.
	BlockByID(types.BlockID) (types.Block, uint64, bool)

	// ChildTarget returns the target required to extend the current heaviest
	// fork. This function is typically used by miners looking to extend the
	// heaviest fork.
	ChildTarget(types.BlockID) (Target, bool)

	// Close will shut down the consensus set, giving the module enough time to
	// run any required closing routines.
	Close() error

	// ConsensusSetSubscribe adds a subscriber to the list of subscribers
	// and gives them every consensus change that has occurred since the
	// change with the provided id. There are a few special cases,
	// described by the ConsensusChangeX variables in this package.
	// A channel can be provided to abort the subscription process.
	ConsensusSetSubscribe(ConsensusSetSubscriber, ConsensusChangeID, <-chan struct{}) error

	// CurrentBlock returns the latest block in the heaviest known
	// blockchain.
	CurrentBlock() types.Block

	// Height returns the current height of consensus.
	Height() uint64

	// Synced returns true if the consensus set is synced with the network.
	Synced() bool

	// InCurrentPath returns true if the block id presented is found in the
	// current path, false otherwise.
	InCurrentPath(types.BlockID) bool

	// MinimumValidChildTimestamp returns the earliest timestamp that is
	// valid on the current longest fork according to the consensus set. This is
	// a required piece of information for the miner, who could otherwise be at
	// risk of mining invalid blocks.
	MinimumValidChildTimestamp(types.BlockID) (time.Time, bool)

	// StorageProofSegment returns the segment to be used in the storage proof for
	// a given file contract.
	StorageProofSegment(types.FileContractID) (uint64, error)

	// FoundationUnlockHashes returns the current primary and failsafe
	// Foundation UnlockHashes.
	FoundationUnlockHashes() (primary, failsafe types.Address)

	// TryTransactionSet checks whether the transaction set would be valid if
	// it were added in the next block. A consensus change is returned
	// detailing the diffs that would result from the application of the
	// transaction.
	TryTransactionSet([]types.Transaction) (ConsensusChange, error)

	// Unsubscribe removes a subscriber from the list of subscribers,
	// allowing for garbage collection and rescanning. If the subscriber is
	// not found in the subscriber database, no action is taken.
	Unsubscribe(ConsensusSetSubscriber)
}

A ConsensusSet accepts blocks and builds an understanding of network consensus.

type ConsensusSetSubscriber

type ConsensusSetSubscriber interface {
	// ProcessConsensusChange sends a consensus update to a module through
	// a function call. Updates will always be sent in the correct order.
	// There may not be any reverted blocks, but there will always be
	// applied blocks.
	ProcessConsensusChange(ConsensusChange)
}

A ConsensusSetSubscriber is an object that receives updates to the consensus set every time there is a change in consensus.

type ContractMetadata

type ContractMetadata struct {
	ID      types.FileContractID
	HostKey types.PublicKey

	StartHeight uint64
	RenewedFrom types.FileContractID

	UploadSpending      types.Currency
	DownloadSpending    types.Currency
	FundAccountSpending types.Currency
	TotalCost           types.Currency
}

ContractMetadata contains all metadata needed to re-create a contract.

func (ContractMetadata) DecodeFrom

func (cm ContractMetadata) DecodeFrom(d *types.Decoder)

DecodeFrom implements requestBody.

func (ContractMetadata) EncodeTo

func (cm ContractMetadata) EncodeTo(e *types.Encoder)

EncodeTo implements requestBody.

type ContractUtility

type ContractUtility struct {
	GoodForUpload bool
	GoodForRenew  bool

	// BadContract will be set to true if there's good reason to believe that
	// the contract is unusable and will continue to be unusable. For example,
	// if the host is claiming that the contract does not exist, the contract
	// should be marked as bad.
	BadContract bool
	LastOOSErr  uint64 // OOS means Out Of Storage.

	// If a contract is locked, the utility should not be updated. 'Locked' is a
	// value that gets persisted.
	Locked bool
}

ContractUtility contains metrics internal to the contractor that reflect the utility of a given contract.

type ContractWatchStatus

type ContractWatchStatus struct {
	Archived                  bool
	FormationSweepHeight      uint64
	ContractFound             bool
	LatestRevisionFound       uint64
	StorageProofFoundAtHeight uint64
	DoubleSpendHeight         uint64
	WindowStart               uint64
	WindowEnd                 uint64
}

ContractWatchStatus provides information about the status of a contract in the manager's watchdog.

type CreditData

type CreditData struct {
	Amount    float64 `json:"amount"`
	Remaining uint64  `json:"remaining"`
}

CreditData contains the information about any running promotion.

type DelayedSiacoinOutputDiff

type DelayedSiacoinOutputDiff struct {
	Direction      DiffDirection
	ID             types.SiacoinOutputID
	SiacoinOutput  types.SiacoinOutput
	MaturityHeight uint64
}

A DelayedSiacoinOutputDiff indicates the introduction of a siacoin output that cannot be spent until after maturing for 144 blocks. When the output has matured, a SiacoinOutputDiff will be provided.

func (*DelayedSiacoinOutputDiff) DecodeFrom

func (dsod *DelayedSiacoinOutputDiff) DecodeFrom(d *types.Decoder)

DecodeFrom implements types.DecoderFrom.

func (*DelayedSiacoinOutputDiff) EncodeTo

func (dsod *DelayedSiacoinOutputDiff) EncodeTo(e *types.Encoder)

EncodeTo implements types.EncoderTo.

type DiffDirection

type DiffDirection bool

A DiffDirection indicates the "direction" of a diff, either applied or reverted. A bool is used to restrict the value to these two possibilities.

const (
	// ConsensusDir is the name of the directory used for all of the consensus
	// persistence files.
	ConsensusDir = "consensus"

	// DiffApply indicates that a diff is being applied to the consensus set.
	DiffApply DiffDirection = true

	// DiffRevert indicates that a diff is being reverted from the consensus
	// set.
	DiffRevert DiffDirection = false
)

type EncryptionManager

type EncryptionManager interface {
	// Encrypt will encrypt the wallet using the input key. Upon
	// encryption, a primary seed will be created for the wallet (no seed
	// exists prior to this point). If the key is blank, then the hash of
	// the seed that is generated will be used as the key.
	//
	// Encrypt can only be called once throughout the life of the wallet
	// and will return an error on subsequent calls (even after restarting
	// the wallet). To reset the wallet, the wallet must be deleted.
	Encrypt(masterKey WalletKey) (Seed, error)

	// Reset will reset the wallet, clearing the database and returning it to
	// the unencrypted state. Reset can only be called on a wallet that has
	// already been encrypted.
	Reset() error

	// Encrypted returns whether or not the wallet has been encrypted yet.
	// After being encrypted for the first time, the wallet can only be
	// unlocked using the encryption password.
	Encrypted() (bool, error)

	// InitFromSeed functions like Encrypt, but using a specified seed.
	// Unlike Encrypt, the blockchain will be scanned to determine the
	// seed's progress. For this reason, InitFromSeed should not be called
	// until the blockchain is fully synced.
	InitFromSeed(masterKey WalletKey, seed Seed) error

	// Lock deletes all keys in memory and prevents the wallet from being
	// used to spend coins or extract keys until 'Unlock' is called.
	Lock() error

	// Unlock must be called before the wallet is usable. All wallets and
	// wallet seeds are encrypted by default, and the wallet will not know
	// which addresses to watch for on the blockchain until unlock has been
	// called.
	//
	// All items in the wallet are encrypted using different keys which are
	// derived from the master key.
	Unlock(masterKey WalletKey) error

	// UnlockAsync must be called before the wallet is usable. All wallets and
	// wallet seeds are encrypted by default, and the wallet will not know
	// which addresses to watch for on the blockchain until unlock has been
	// called.
	// UnlockAsync will return a channel as soon as the wallet is unlocked but
	// before the wallet is caught up to consensus.
	//
	// All items in the wallet are encrypted using different keys which are
	// derived from the master key.
	UnlockAsync(masterKey WalletKey) <-chan error

	// ChangeKey changes the wallet's materKey from masterKey to newKey,
	// re-encrypting the wallet with the provided key.
	ChangeKey(masterKey WalletKey, newKey WalletKey) error

	// IsMasterKey verifies that the masterKey is the key used to encrypt
	// the wallet.
	IsMasterKey(masterKey WalletKey) (bool, error)

	// ChangeKeyWithSeed is the same as ChangeKey but uses the primary seed
	// instead of the current masterKey.
	ChangeKeyWithSeed(seed Seed, newKey WalletKey) error

	// Unlocked returns true if the wallet is currently unlocked, false
	// otherwise.
	Unlocked() (bool, error)
}

EncryptionManager can encrypt, lock, unlock, and indicate the current status of the EncryptionManager.

type ExtendedContract

type ExtendedContract struct {
	Contract            rhpv2.ContractRevision
	StartHeight         uint64
	TotalCost           types.Currency
	UploadSpending      types.Currency
	DownloadSpending    types.Currency
	FundAccountSpending types.Currency
	RenewedFrom         types.FileContractID
}

ExtendedContract contains the contract and its metadata.

func (ExtendedContract) DecodeFrom

func (ec ExtendedContract) DecodeFrom(d *types.Decoder)

DecodeFrom implements requestBody.

func (ExtendedContract) EncodeTo

func (ec ExtendedContract) EncodeTo(e *types.Encoder)

EncodeTo implements requestBody.

type ExtendedContractSet

type ExtendedContractSet struct {
	Contracts []ExtendedContract
}

ExtendedContractSet is a collection of extendedContracts.

func (ExtendedContractSet) DecodeFrom

func (ecs ExtendedContractSet) DecodeFrom(d *types.Decoder)

DecodeFrom implements requestBody.

func (ExtendedContractSet) EncodeTo

func (ecs ExtendedContractSet) EncodeTo(e *types.Encoder)

EncodeTo implements requestBody.

type FileContractDiff

type FileContractDiff struct {
	Direction    DiffDirection
	ID           types.FileContractID
	FileContract types.FileContract
}

A FileContractDiff indicates the addition or removal of a FileContract in the consensus set.

func (*FileContractDiff) DecodeFrom

func (fcd *FileContractDiff) DecodeFrom(d *types.Decoder)

DecodeFrom implements types.DecoderFrom.

func (*FileContractDiff) EncodeTo

func (fcd *FileContractDiff) EncodeTo(e *types.Encoder)

EncodeTo implements types.EncoderTo.

type FileMetadata

type FileMetadata struct {
	Key   types.Hash256 `json:"key"`
	Path  string        `json:"path"`
	Slabs []Slab        `json:"slabs"`
}

FileMetadata contains the uploaded file metadata.

func (*FileMetadata) DecodeFrom

func (fm *FileMetadata) DecodeFrom(d *types.Decoder)

DecodeFrom implements types.ProtocolObject.

func (*FileMetadata) EncodeTo

func (fm *FileMetadata) EncodeTo(e *types.Encoder)

EncodeTo implements types.ProtocolObject.

type FilterMode

type FilterMode int

FilterMode is the helper type for the enum constants for the HostDB filter mode.

const (
	HostDBFilterError FilterMode = iota
	HostDBDisableFilter
	HostDBActivateBlacklist
	HostDBActiveWhitelist
)

HostDBFilterError HostDBDisableFilter HostDBActivateBlacklist and HostDBActiveWhitelist are the constants used to enable and disable the filter mode of the manager's hostdb.

func (*FilterMode) FromString

func (fm *FilterMode) FromString(s string) error

FromString assigned the FilterMode from the provide string.

func (FilterMode) String

func (fm FilterMode) String() string

String returns the string value for the FilterMode.

type Gateway

type Gateway interface {
	Alerter

	// Connect establishes a persistent connection to a peer.
	Connect(NetAddress) error

	// ConnectManual is a Connect wrapper for a user-initiated Connect.
	ConnectManual(NetAddress) error

	// Disconnect terminates a connection to a peer.
	Disconnect(NetAddress) error

	// DiscoverAddress discovers and returns the current public IP address
	// of the gateway. Contrary to Address, DiscoverAddress is blocking and
	// might take multiple minutes to return. A channel to cancel the
	// discovery can be supplied optionally.
	DiscoverAddress(cancel <-chan struct{}) (net.IP, error)

	// ForwardPort adds a port mapping to the router. It will block until
	// the mapping is established or until it is interrupted by a shutdown.
	ForwardPort(port string) error

	// DisconnectManual is a Disconnect wrapper for a user-initiated
	// disconnect.
	DisconnectManual(NetAddress) error

	// AddToBlocklist adds addresses to the blocklist of the gateway.
	AddToBlocklist(addresses []string) error

	// Blocklist returns the current blocklist of the Gateway.
	Blocklist() ([]string, error)

	// RemoveFromBlocklist removes addresses from the blocklist of the
	// gateway.
	RemoveFromBlocklist(addresses []string) error

	// SetBlocklist sets the blocklist of the gateway.
	SetBlocklist(addresses []string) error

	// Address returns the Gateway's address.
	Address() NetAddress

	// Peers returns the addresses that the Gateway is currently connected
	// to.
	Peers() []Peer

	// RegisterRPC registers a function to handle incoming connections that
	// supply the given RPC ID.
	RegisterRPC(string, RPCFunc)

	// UnregisterRPC unregisters an RPC and removes all references to the
	// RPCFunc supplied in the corresponding RegisterRPC call. References to
	// RPCFuncs registered with RegisterConnectCall are not removed and
	// should be removed with UnregisterConnectCall. If the RPC does not
	// exist no action is taken.
	UnregisterRPC(string)

	// RegisterConnectCall registers an RPC name and function to be called
	// upon connecting to a peer.
	RegisterConnectCall(string, RPCFunc)

	// UnregisterConnectCall unregisters an RPC and removes all references to the
	// RPCFunc supplied in the corresponding RegisterConnectCall call. References
	// to RPCFuncs registered with RegisterRPC are not removed and should be
	// removed with UnregisterRPC. If the RPC does not exist no action is taken.
	UnregisterConnectCall(string)

	// RPC calls an RPC on the given address. RPC cannot be called on an
	// address that the Gateway is not connected to.
	RPC(NetAddress, string, RPCFunc) error

	// Broadcast transmits obj, prefaced by the RPC name, to all of the
	// given peers in parallel.
	Broadcast(name string, obj types.EncoderTo, peers []Peer)

	// Online returns true if the gateway is connected to remote hosts.
	Online() bool

	// Close safely stops the Gateway's listener process.
	Close() error
}

A Gateway facilitates the interactions between the local node and remote nodes (peers). It relays incoming blocks and transactions to local modules, and broadcasts outgoing blocks and transactions to peers. In a broad sense, it is responsible for ensuring that the local consensus set is consistent with the "network" consensus set.

type GenericAlerter

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

GenericAlerter implements the Alerter interface. It can be used as a helper type to implement the Alerter interface for modules and submodules.

func NewAlerter

func NewAlerter(module string) *GenericAlerter

NewAlerter creates a new alerter.

func (*GenericAlerter) Alerts

func (a *GenericAlerter) Alerts() (crit, err, warn, info []Alert)

Alerts returns the current alerts tracked by the alerter.

func (*GenericAlerter) RegisterAlert

func (a *GenericAlerter) RegisterAlert(id AlertID, msg, cause string, severity AlertSeverity)

RegisterAlert adds an alert to the alerter.

func (*GenericAlerter) UnregisterAlert

func (a *GenericAlerter) UnregisterAlert(id AlertID)

UnregisterAlert removes an alert from the alerter by id.

type HostAverages

type HostAverages struct {
	NumHosts               uint64         `json:"numhosts"`
	Duration               uint64         `json:"duration"`
	StoragePrice           types.Currency `json:"storageprice"`
	Collateral             types.Currency `json:"collateral"`
	DownloadBandwidthPrice types.Currency `json:"downloadbandwidthprice"`
	UploadBandwidthPrice   types.Currency `json:"uploadbandwidthprice"`
	ContractPrice          types.Currency `json:"contractprice"`
	BaseRPCPrice           types.Currency `json:"baserpcprice"`
	SectorAccessPrice      types.Currency `json:"sectoraccessprice"`
}

HostAverages contains the host network averages from HostDB.

func (*HostAverages) DecodeFrom

func (ha *HostAverages) DecodeFrom(d *types.Decoder)

DecodeFrom implements types.DecoderFrom.

func (*HostAverages) EncodeTo

func (ha *HostAverages) EncodeTo(e *types.Encoder)

EncodeTo implements types.EncoderTo.

type HostDB

type HostDB interface {
	Alerter

	// ActiveHosts returns the list of hosts that are actively being selected
	// from.
	ActiveHosts() ([]HostDBEntry, error)

	// AllHosts returns the full list of hosts known to the hostdb, sorted in
	// order of preference.
	AllHosts() ([]HostDBEntry, error)

	// CheckForIPViolations accepts a number of host public keys and returns the
	// ones that violate the rules of the addressFilter.
	CheckForIPViolations([]types.PublicKey) ([]types.PublicKey, error)

	// Close closes the hostdb.
	Close() error

	// EstimateHostScore returns the estimated score breakdown of a host with the
	// provided settings.
	EstimateHostScore(Allowance, HostDBEntry) (HostScoreBreakdown, error)

	// Filter returns the hostdb's filterMode and filteredHosts.
	Filter() (FilterMode, map[string]types.PublicKey, []string, error)

	// SetFilterMode sets the renter's hostdb filter mode.
	SetFilterMode(FilterMode, []types.PublicKey, []string) error

	// Host returns the HostDBEntry for a given host.
	Host(pk types.PublicKey) (HostDBEntry, bool, error)

	// IncrementSuccessfulInteractions increments the number of successful
	// interactions with a host for a given key
	IncrementSuccessfulInteractions(types.PublicKey) error

	// IncrementFailedInteractions increments the number of failed interactions with
	// a host for a given key
	IncrementFailedInteractions(types.PublicKey) error

	// initialScanComplete returns a boolean indicating if the initial scan of the
	// hostdb is completed and the current block height of the hostdb.
	InitialScanComplete() (bool, uint64, error)

	// IPViolationsCheck returns a boolean indicating if the IP violation check is
	// enabled or not.
	IPViolationsCheck() (bool, error)

	// RandomHosts returns a set of random hosts, weighted by their estimated
	// usefulness / attractiveness to the renter. RandomHosts will not return
	// any offline or inactive hosts.
	RandomHosts(int, []types.PublicKey, []types.PublicKey) ([]HostDBEntry, error)

	// RandomHostsWithAllowance is the same as RandomHosts but accepts an
	// allowance as an argument to be used instead of the allowance set in the
	// manager.
	RandomHostsWithAllowance(int, []types.PublicKey, []types.PublicKey, Allowance) ([]HostDBEntry, error)

	// ScoreBreakdown returns a detailed explanation of the various properties
	// of the host.
	ScoreBreakdown(HostDBEntry) (HostScoreBreakdown, error)

	// SetAllowance updates the allowance used by the hostdb for weighing hosts by
	// updating the host weight function. It will completely rebuild the hosttree so
	// it should be used with care.
	SetAllowance(Allowance) error

	// SetIPViolationCheck enables/disables the IP violation check within the
	// hostdb.
	SetIPViolationCheck(enabled bool) error

	// LoadingComplete indicates if the HostDB has finished loading the hosts
	// from the database.
	LoadingComplete() bool

	// UpdateContracts rebuilds the knownContracts of the HostBD using the
	// provided contracts.
	UpdateContracts([]RenterContract) error
}

A HostDB is a database of hosts that the manager can use for figuring out who to upload to, and download from.

type HostDBEntry

type HostDBEntry struct {
	// Need to wrap rhpv2.HostSettings in a separate named field due to
	// issues with JSON encoding.
	Settings   rhpv2.HostSettings   `json:"settings"`
	PriceTable rhpv3.HostPriceTable `json:"pricetable"`

	// FirstSeen is the first block height at which this host was announced.
	FirstSeen uint64 `json:"firstseen"`

	// LastAnnouncement is the last block height at which this host was announced.
	LastAnnouncement uint64 `json:"lastannouncement"`

	// Measurements that have been taken on the host. The most recent
	// measurements are kept in full detail, historic ones are compressed into
	// the historic values.
	HistoricDowntime time.Duration `json:"historicdowntime"`
	HistoricUptime   time.Duration `json:"historicuptime"`
	ScanHistory      HostDBScans   `json:"scanhistory"`

	// Measurements that are taken whenever we interact with a host.
	HistoricFailedInteractions     float64 `json:"historicfailedinteractions"`
	HistoricSuccessfulInteractions float64 `json:"historicsuccessfulinteractions"`
	RecentFailedInteractions       float64 `json:"recentfailedinteractions"`
	RecentSuccessfulInteractions   float64 `json:"recentsuccessfulinteractions"`

	LastHistoricUpdate uint64 `json:"lasthistoricupdate"`

	// Measurements related to the IP subnet mask.
	IPNets          []string  `json:"ipnets"`
	LastIPNetChange time.Time `json:"lastipnetchange"`

	// The public key of the host, stored separately to minimize risk of certain
	// MitM based vulnerabilities.
	PublicKey types.PublicKey `json:"publickey"`

	// Filtered says whether or not a HostDBEntry is being filtered out of the
	// filtered hosttree due to the filter mode of the hosttree.
	Filtered bool `json:"filtered"`
}

A HostDBEntry represents one host entry in the Manager's host DB. It aggregates the host's external settings and metrics with its public key.

type HostDBScan

type HostDBScan struct {
	Timestamp time.Time `json:"timestamp"`
	Success   bool      `json:"success"`
}

HostDBScan represents a single scan event.

type HostDBScans

type HostDBScans []HostDBScan

HostDBScans represents a sortable slice of scans.

func (HostDBScans) Len

func (s HostDBScans) Len() int

func (HostDBScans) Less

func (s HostDBScans) Less(i, j int) bool

func (HostDBScans) Swap

func (s HostDBScans) Swap(i, j int)

type HostScoreBreakdown

type HostScoreBreakdown struct {
	Score            types.Currency `json:"score"`
	Age              float64        `json:"agescore"`
	Collateral       float64        `json:"collateralscore"`
	Interactions     float64        `json:"interactionscore"`
	StorageRemaining float64        `json:"storageremainingscore"`
	Uptime           float64        `json:"uptimescore"`
	Version          float64        `json:"versionscore"`
	Prices           float64        `json:"pricescore"`
}

HostScoreBreakdown breaks down the host scores.

type KeyManager

type KeyManager interface {
	// AllAddresses returns all addresses that the wallet is able to spend
	// from, including unseeded addresses. Addresses are returned sorted in
	// byte-order.
	AllAddresses() ([]types.Address, error)

	// AllSeeds returns all of the seeds that are being tracked by the
	// wallet, including the primary seed. Only the primary seed is used to
	// generate new addresses, but the wallet can spend funds sent to
	// public keys generated by any of the seeds returned.
	AllSeeds() ([]Seed, error)

	// LastAddresses returns the last n addresses starting at the last seedProgress
	// for which an address was generated.
	LastAddresses(n uint64) ([]types.Address, error)

	// LoadSeed will recreate a wallet file using the recovery phrase.
	// LoadSeed only needs to be called if the original seed file or
	// encryption password was lost. The master key is used to encrypt the
	// recovery seed before saving it to disk.
	LoadSeed(WalletKey, Seed) error

	// MarkAddressUnused marks the provided address as unused which causes it to be
	// handed out by a subsequent call to `NextAddresses` again.
	MarkAddressUnused(...types.UnlockConditions) error

	// NextAddress returns a new coin address generated from the
	// primary seed.
	NextAddress() (types.UnlockConditions, error)

	// NextAddresses returns n new coin addresses generated from the
	// primary seed.
	NextAddresses(uint64) ([]types.UnlockConditions, error)

	// PrimarySeed returns the unencrypted primary seed of the wallet,
	// along with a uint64 indicating how many addresses may be safely
	// generated from the seed.
	PrimarySeed() (Seed, uint64, error)

	// SignTransaction adds a signature to each of the specified inputs.
	SignTransaction(txn *types.Transaction, toSign []types.Hash256, cf types.CoveredFields) error

	// SweepSeed scans the blockchain for outputs generated from seed and
	// creates a transaction that transfers them to the wallet. Note that
	// this incurs a transaction fee. It returns the total value of the
	// outputs, minus the fee. If only Siafunds were found, the fee is
	// deducted from the wallet.
	SweepSeed(seed Seed) (coins types.Currency, funds uint64, err error)
}

KeyManager manages wallet keys, including the use of seeds, creating and loading backups, and providing a layer of compatibility for older wallet files.

type MaintenanceSpending

type MaintenanceSpending struct {
	AccountBalanceCost   types.Currency
	FundAccountCost      types.Currency
	UpdatePriceTableCost types.Currency
}

MaintenanceSpending is a helper struct that contains a breakdown of costs related to the maintenance (a.k.a upkeep) of the RHP3 protocol. This includes the costs to sync the account balance, update the price table, etc.

func (MaintenanceSpending) Add

Add is a convenience function that sums the fields of the spending object with the corresponding fields of the given object.

func (MaintenanceSpending) Sum

Sum is a convenience function that sums up all of the fields in the spending object and returns the total as a types.Currency.

type Manager

type Manager interface {
	Alerter

	// AcceptContracts accepts a set of contracts from the renter
	// and adds them to the contract set.
	AcceptContracts(types.PublicKey, []ContractMetadata)

	// ActiveHosts returns an array of HostDB's active hosts.
	ActiveHosts() ([]HostDBEntry, error)

	// AllHosts returns an array of all hosts.
	AllHosts() ([]HostDBEntry, error)

	// BlockHeight returns the current block height.
	BlockHeight() uint64

	// Close safely shuts down the manager.
	Close() error

	// Contracts returns storage contracts.
	Contracts() []RenterContract

	// ContractsByRenter returns storage contracts filtered by the renter.
	ContractsByRenter(types.PublicKey) []RenterContract

	// CreateNewRenter inserts a new renter into the map.
	CreateNewRenter(string, types.PublicKey)

	// DeleteMetadata deletes the renter's saved file metadata.
	DeleteMetadata(types.PublicKey)

	// DeleteObject deletes the saved file metadata object.
	DeleteObject(types.PublicKey, string) error

	// DeleteRenter deletes the renter data from the memory.
	DeleteRenter(string)

	// FeeEstimation returns the minimum and the maximum estimated fees for
	// a transaction.
	FeeEstimation() (min, max types.Currency)

	// Filter returns the HostDB's filterMode and filteredHosts.
	Filter() (FilterMode, map[string]types.PublicKey, []string, error)

	// FormContract forms a contract with the specified host.
	FormContract(*RPCSession, types.PublicKey, types.PublicKey, types.PublicKey, uint64, uint64, uint64, uint64, uint64, uint64) (RenterContract, error)

	// FormContracts forms the required number of contracts with the hosts.
	FormContracts(types.PublicKey, types.PrivateKey, Allowance) ([]RenterContract, error)

	// GetAverages retrieves the host network averages.
	GetAverages() HostAverages

	// GetBalance retrieves the balance information on the account.
	GetBalance(string) (UserBalance, error)

	// GetExchangeRate returns the exchange rate of a given currency.
	GetExchangeRate(string) (float64, error)

	// GetRenter returns the renter by the public key.
	GetRenter(types.PublicKey) (Renter, error)

	// GetSiacoinRate calculates the SC price in a given currency.
	GetSiacoinRate(string) (float64, error)

	// GetSpendings retrieves the user's spendings.
	GetSpendings(string) (UserSpendings, error)

	// GetWalletSeed returns the wallet seed.
	GetWalletSeed() (Seed, error)

	// Host returns the host associated with the given public key.
	Host(types.PublicKey) (HostDBEntry, bool, error)

	// IncrementStats increments the number of formed or renewed contracts.
	IncrementStats(string, bool) error

	// InitialScanComplete returns a boolean indicating if the initial scan of the
	// HostDB is completed.
	InitialScanComplete() (bool, uint64, error)

	// LockSiacoins moves a part of the balance to "locked".
	LockSiacoins(string, float64) error

	// OldContracts returns the contracts that have expired.
	OldContracts() []RenterContract

	// OldContractsByRenter returns expired contracts filtered by the renter.
	OldContractsByRenter(types.PublicKey) []RenterContract

	// RandomHosts picks up to the specified number of random hosts from the
	// hostdb sorted by weight.
	RandomHosts(uint64, Allowance) ([]HostDBEntry, error)

	// RefreshedContract returns a bool indicating if the contract was refreshed.
	RefreshedContract(types.FileContractID) bool

	// RenewContract renews a contract.
	RenewContract(*RPCSession, types.PublicKey, types.FileContractID, uint64, uint64, uint64, uint64, uint64, uint64) (RenterContract, error)

	// RenewContracts renews a set of contracts and returns a new set.
	RenewContracts(types.PublicKey, types.PrivateKey, Allowance, []types.FileContractID) ([]RenterContract, error)

	// RenewedFrom returns the ID of the contract the given contract was renewed
	// from, if any.
	RenewedFrom(types.FileContractID) types.FileContractID

	// Renters retrieves the list of renters.
	Renters() []Renter

	// RetrieveMetadata retrieves the file metadata from the database.
	RetrieveMetadata(types.PublicKey, []string) ([]FileMetadata, error)

	// RetrieveSpendings retrieves the user's spendings.
	RetrieveSpendings(string, string) (UserSpendings, error)

	// ScoreBreakdown returns the score breakdown of the specific host.
	ScoreBreakdown(HostDBEntry) (HostScoreBreakdown, error)

	// SetAllowance sets the renter's allowance.
	SetAllowance(types.PublicKey, Allowance) error

	// SetFilterMode sets the HostDB's filter mode.
	SetFilterMode(FilterMode, []types.PublicKey, []string) error

	// UnlockSiacoins moves a part of the amount from "locked" to "available",
	// while the other part (fees and other spent funds) is "burned".
	UnlockSiacoins(string, float64, float64, uint64) error

	// UpdateBalance updates the balance information on the account.
	UpdateBalance(email string, ub UserBalance) error

	// UpdateContract updates the contract with the new revision and spending
	// details.
	UpdateContract(types.FileContractRevision, []types.TransactionSignature, types.Currency, types.Currency, types.Currency) error

	// UpdateMetadata updates the file metadata in the database.
	UpdateMetadata(types.PublicKey, FileMetadata) error

	// UpdateRenterSettings updates the renter's opt-in settings.
	UpdateRenterSettings(types.PublicKey, RenterSettings, types.PrivateKey, types.PrivateKey) error

	// UpdateSlab updates a file slab after a successful migration.
	UpdateSlab(types.PublicKey, Slab) error

	// UpdateSpendings updates the user's spendings.
	UpdateSpendings(string, UserSpendings) error
}

Manager implements the methods necessary to communicate with the hosts.

type MerkleTree

type MerkleTree struct {
	merkletree.Tree
}

MerkleTree wraps merkletree.Tree, changing some of the function definitions to assume sia-specific constants and return sia-specific types.

func NewTree

func NewTree() *MerkleTree

NewTree returns a MerkleTree, which can be used for getting Merkle roots and Merkle proofs on data. See merkletree.Tree for more details.

func (*MerkleTree) PushObject

func (t *MerkleTree) PushObject(obj types.EncoderTo)

PushObject encodes and adds the hash of the encoded object to the tree as a leaf.

func (*MerkleTree) Root

func (t *MerkleTree) Root() (h types.Hash256)

Root is a redefinition of merkletree.Tree.Root, returning a types.Hash256 instead of a []byte.

type NetAddress

type NetAddress string

A NetAddress contains the information needed to contact a peer.

func DecodeAnnouncement

func DecodeAnnouncement(fullAnnouncement []byte) (na NetAddress, pk types.PublicKey, err error)

DecodeAnnouncement decodes announcement bytes into a host announcement, verifying the prefix and the signature.

func (NetAddress) Host

func (na NetAddress) Host() string

Host removes the port from a NetAddress, returning just the host. If the address is not of the form "host:port" the empty string is returned. The port will still be returned for invalid NetAddresses (e.g. "unqualified:0" will return "unqualified"), but in general you should only call Host on valid addresses.

func (NetAddress) IsLocal

func (na NetAddress) IsLocal() bool

IsLocal returns true if the input IP address belongs to a local address range such as 192.168.x.x or 127.x.x.x.

func (NetAddress) IsLoopback

func (na NetAddress) IsLoopback() bool

IsLoopback returns true for IP addresses that are on the same machine.

func (NetAddress) IsStdValid

func (na NetAddress) IsStdValid() error

IsStdValid returns an error if the NetAddress is invalid. A valid NetAddress is of the form "host:port", such that "host" is either a valid IPv4/IPv6 address or a valid hostname, and "port" is an integer in the range [1,65535]. Valid IPv4 addresses, IPv6 addresses, and hostnames are detailed in RFCs 791, 2460, and 952, respectively. Loopback addresses are allowed.

func (NetAddress) IsValid

func (na NetAddress) IsValid() error

IsValid is an extension to IsStdValid that also forbids the loopback address.

NOTE: IsValid is being phased out in favor of allowing the loopback address but verifying through other means that the connection is not to yourself (which is the original reason that the loopback address was banned).

func (NetAddress) Port

func (na NetAddress) Port() string

Port returns the NetAddress object's port number. If the address is not of the form "host:port" the empty string is returned. The port will still be returned for invalid NetAddresses (e.g. "localhost:0" will return "0"), but in general you should only call Port on valid addresses.

type Peer

type Peer struct {
	Inbound    bool       `json:"inbound"`
	Local      bool       `json:"local"`
	NetAddress NetAddress `json:"netaddress"`
	Version    string     `json:"version"`
}

Peer contains all the info necessary to Broadcast to a peer.

type PeerConn

type PeerConn interface {
	net.Conn
	RPCAddr() NetAddress
}

A PeerConn is the connection type used when communicating with peers during an RPC. It is identical to a net.Conn with the additional RPCAddr method. This method acts as an identifier for peers and is the address that the peer can be dialed on. It is also the address that should be used when calling an RPC on the peer.

type Portal

type Portal interface {
	Alerter

	// Close safely shuts down the portal.
	Close() error

	// GetCredits retrieves the promotion data.
	GetCredits() CreditData

	// SetCredits updates the promotion data.
	SetCredits(CreditData)
}

Portal implements the portal server.

type ProcessedInput

type ProcessedInput struct {
	ParentID       types.Hash256   `json:"parentid"`
	FundType       types.Specifier `json:"fundtype"`
	WalletAddress  bool            `json:"walletaddress"`
	RelatedAddress types.Address   `json:"relatedaddress"`
	Value          types.Currency  `json:"value"`
}

A ProcessedInput represents funding to a transaction. The input is coming from an address and going to the outputs. The fund types are 'SiacoinInput', 'SiafundInput'.

func (*ProcessedInput) DecodeFrom

func (pi *ProcessedInput) DecodeFrom(d *types.Decoder)

DecodeFrom implements types.DecoderFrom interface.

func (*ProcessedInput) EncodeTo

func (pi *ProcessedInput) EncodeTo(e *types.Encoder)

EncodeTo implements types.EncoderTo interface.

type ProcessedOutput

type ProcessedOutput struct {
	ID             types.Hash256   `json:"id"`
	FundType       types.Specifier `json:"fundtype"`
	MaturityHeight uint64          `json:"maturityheight"`
	WalletAddress  bool            `json:"walletaddress"`
	RelatedAddress types.Address   `json:"relatedaddress"`
	Value          types.Currency  `json:"value"`
}

A ProcessedOutput is a Siacoin output that appears in a transaction. Some outputs mature immediately, some are delayed, and some may never mature at all (in the event of storage proofs).

Fund type can either be 'SiacoinOutput', 'SiafundOutput', 'ClaimOutput', 'MinerPayout', or 'MinerFee'. All outputs except the miner fee create outputs accessible to an address. Miner fees are not spendable, and instead contribute to the block subsidy.

MaturityHeight indicates at what block height the output becomes available. SiacoinInputs and SiafundInputs become available immediately. ClaimInputs and MinerPayouts become available after 144 confirmations.

func (*ProcessedOutput) DecodeFrom

func (po *ProcessedOutput) DecodeFrom(d *types.Decoder)

DecodeFrom implements types.DecoderFrom interface.

func (*ProcessedOutput) EncodeTo

func (po *ProcessedOutput) EncodeTo(e *types.Encoder)

EncodeTo implements types.EncoderTo interface.

type ProcessedTransaction

type ProcessedTransaction struct {
	Transaction           types.Transaction   `json:"transaction"`
	TransactionID         types.TransactionID `json:"transactionid"`
	ConfirmationHeight    uint64              `json:"confirmationheight"`
	ConfirmationTimestamp time.Time           `json:"confirmationtimestamp"`

	Inputs  []ProcessedInput  `json:"inputs"`
	Outputs []ProcessedOutput `json:"outputs"`
}

A ProcessedTransaction is a transaction that has been processed into explicit inputs and outputs and tagged with some header data such as confirmation height + timestamp.

Because of the block subsidy, a block is considered as a transaction. Since there is technically no transaction id for the block subsidy, the block id is used instead.

func (*ProcessedTransaction) DecodeFrom

func (pt *ProcessedTransaction) DecodeFrom(d *types.Decoder)

DecodeFrom implements types.DecoderFrom interface.

func (*ProcessedTransaction) EncodeTo

func (pt *ProcessedTransaction) EncodeTo(e *types.Encoder)

EncodeTo implements types.EncoderTo interface.

type Provider

type Provider interface {
	Alerter

	// Close safely shuts down the provider.
	Close() error

	// PublicKey returns the provider's public key.
	PublicKey() types.PublicKey

	// SecretKey returns the provider's secret key.
	SecretKey() types.PrivateKey
}

Provider implements the methods necessary to communicate with the renters.

type RPCError

type RPCError struct {
	Type        types.Specifier
	Data        []byte
	Description string
}

RPCError is the generic error transferred in an RPC.

func (*RPCError) DecodeFrom

func (re *RPCError) DecodeFrom(d *types.Decoder)

DecodeFrom implements types.DecoderFrom.

func (*RPCError) EncodeTo

func (re *RPCError) EncodeTo(e *types.Encoder)

EncodeTo implements types.EncoderTo.

func (*RPCError) Error

func (e *RPCError) Error() string

Error implements the error interface.

type RPCFunc

type RPCFunc func(PeerConn) error

RPCFunc is the type signature of functions that handle RPCs. It is used for both the caller and the callee. RPCFuncs may perform locking. RPCFuncs may close the connection early, and it is recommended that they do so to avoid keeping the connection open after all necessary I/O has been performed.

type RPCResponse

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

RPCResponse if a helper type for encoding and decoding RPC response messages, which can represent either valid data or an error.

func (*RPCResponse) DecodeFrom

func (resp *RPCResponse) DecodeFrom(d *types.Decoder)

DecodeFrom implements types.DecoderFrom.

func (*RPCResponse) EncodeTo

func (resp *RPCResponse) EncodeTo(e *types.Encoder)

EncodeTo implements types.EncoderTo.

type RPCSession

type RPCSession struct {
	Conn      net.Conn
	Aead      cipher.AEAD
	Challenge [16]byte
}

An RPCSession contains the state of an RPC session with a renter.

func (*RPCSession) ReadMessage

func (s *RPCSession) ReadMessage(message RequestBody, maxLen uint64) error

readMessage reads an encrypted message from the renter.

func (*RPCSession) ReadRequest

func (s *RPCSession) ReadRequest(req RequestBody, maxLen uint64) (types.Hash256, error)

ReadRequest reads an encrypted RPC request from the renter.

func (*RPCSession) ReadResponse

func (s *RPCSession) ReadResponse(resp RequestBody, maxLen uint64) error

ReadResponse reads an encrypted RPC response from the renter.

func (*RPCSession) WriteError

func (s *RPCSession) WriteError(err error) error

WriteError sends an error message to the renter.

func (*RPCSession) WriteMessage

func (s *RPCSession) WriteMessage(message RequestBody) error

writeMessage sends an encrypted message to the renter.

func (*RPCSession) WriteResponse

func (s *RPCSession) WriteResponse(resp RequestBody) error

WriteResponse sends an encrypted RPC responce to the renter.

type Renter

type Renter struct {
	Allowance     Allowance
	CurrentPeriod uint64
	PublicKey     types.PublicKey
	Email         string // Link to the user account.
	Settings      RenterSettings
	PrivateKey    types.PrivateKey
	AccountKey    types.PrivateKey
}

Renter holds the data related to the specific renter.

func (*Renter) ContractEndHeight

func (r *Renter) ContractEndHeight() uint64

contractEndHeight returns the height at which the renter's contracts end.

type RenterContract

type RenterContract struct {
	ID              types.FileContractID
	HostPublicKey   types.PublicKey
	RenterPublicKey types.PublicKey
	Transaction     types.Transaction

	StartHeight uint64
	EndHeight   uint64

	// RenterFunds is the amount remaining in the contract that the renter can
	// spend.
	RenterFunds types.Currency

	// The FileContract does not indicate what funds were spent on, so we have
	// to track the various costs manually.
	DownloadSpending    types.Currency
	FundAccountSpending types.Currency
	MaintenanceSpending MaintenanceSpending
	StorageSpending     types.Currency
	UploadSpending      types.Currency

	// Utility contains utility information about the renter.
	Utility ContractUtility

	// TotalCost indicates the amount of money that the renter spent and/or
	// locked up while forming a contract. This includes fees, and includes
	// funds which were allocated (but not necessarily committed) to spend on
	// uploads/downloads/storage.
	TotalCost types.Currency

	// ContractFee is the amount of money paid to the host to cover potential
	// future transaction fees that the host may incur, and to cover any other
	// overheads the host may have.
	//
	// TxnFee is the amount of money spent on the transaction fee when putting
	// the renter contract on the blockchain.
	//
	// SiafundFee is the amount of money spent on siafund fees when creating the
	// contract. The siafund fee that the renter pays covers both the renter and
	// the host portions of the contract, and therefore can be unexpectedly high
	// if the the host collateral is high.
	ContractFee types.Currency
	TxnFee      types.Currency
	SiafundFee  types.Currency
}

A RenterContract contains metadata about a file contract. It is read-only; modifying a RenterContract does not modify the actual file contract.

func (*RenterContract) Size

func (rc *RenterContract) Size() uint64

Size returns the contract size.

type RenterSettings

type RenterSettings struct {
	AutoRenewContracts bool `json:"autorenew"`
	BackupFileMetadata bool `json:"backupmetadata"`
	AutoRepairFiles    bool `json:"autorepair"`
}

RenterSettings keep the opt-in settings of the renter.

type RenterSpending

type RenterSpending struct {
	// ContractFees are the sum of all fees in the contract. This means it
	// includes the ContractFee, TxnFee and SiafundFee
	ContractFees types.Currency
	// DownloadSpending is the money currently spent on downloads.
	DownloadSpending types.Currency
	// FundAccountSpending is the money used to fund an ephemeral account on the
	// host.
	FundAccountSpending types.Currency
	// MaintenanceSpending is the money spent on maintenance tasks in support of
	// the RHP3 protocol, this includes updating the price table as well as
	// syncing the ephemeral account balance.
	MaintenanceSpending MaintenanceSpending
	// StorageSpending is the money currently spent on storage.
	StorageSpending types.Currency
	// ContractSpending is the total amount of money that the renter has put
	// into contracts, whether it's locked and the renter gets that money
	// back or whether it's spent and the renter won't get the money back.
	TotalAllocated types.Currency
	// UploadSpending is the money currently spent on uploads.
	UploadSpending types.Currency
	// Unspent is locked-away, unspent money.
	Unspent types.Currency
	// WithheldFunds are the funds from the previous period that are tied up
	// in contracts and have not been released yet
	WithheldFunds types.Currency
	// ReleaseBlock is the block at which the WithheldFunds should be
	// released to the renter, based on worst case.
	// Contract End Height + Host Window Size + Maturity Delay
	ReleaseBlock uint64
	// PreviousSpending is the total spend funds from old contracts
	// that are not included in the current period spending
	PreviousSpending types.Currency
}

RenterSpending contains the metrics about how much the renter has spent during the current billing period.

func (RenterSpending) SpendingBreakdown

func (rs RenterSpending) SpendingBreakdown() (totalSpent, unspentAllocated, unspentUnallocated types.Currency)

SpendingBreakdown provides a breakdown of a few fields in the RenterSpending.

type RequestBody

type RequestBody interface {
	DecodeFrom(d *types.Decoder)
	EncodeTo(e *types.Encoder)
}

RequestBody is the common interface type for the renter requests.

type Seed

type Seed [16]byte

Seed is cryptographic entropy that is used to derive spendable wallet addresses.

func DecodeBIP39Phrase

func DecodeBIP39Phrase(phrase string) (Seed, error)

DecodeBIP39Phrase converts a seed phrase into a byte slice.

type Shard

type Shard struct {
	Host types.PublicKey `json:"host"`
	Root types.Hash256   `json:"root"`
}

Shard represents an individual shard.

func (*Shard) DecodeFrom

func (ss *Shard) DecodeFrom(d *types.Decoder)

DecodeFrom implements types.ProtocolObject.

func (*Shard) EncodeTo

func (ss *Shard) EncodeTo(e *types.Encoder)

EncodeTo implements types.ProtocolObject.

type SiacoinOutputDiff

type SiacoinOutputDiff struct {
	Direction     DiffDirection
	ID            types.SiacoinOutputID
	SiacoinOutput types.SiacoinOutput
}

A SiacoinOutputDiff indicates the addition or removal of a SiacoinOutput in the consensus set.

func (*SiacoinOutputDiff) DecodeFrom

func (sod *SiacoinOutputDiff) DecodeFrom(d *types.Decoder)

DecodeFrom implements types.DecoderFrom.

func (*SiacoinOutputDiff) EncodeTo

func (sod *SiacoinOutputDiff) EncodeTo(e *types.Encoder)

EncodeTo implements types.EncoderTo.

type SiacoinSenderMulti

type SiacoinSenderMulti interface {
	// SendSiacoinsMulti sends coins to multiple addresses.
	SendSiacoinsMulti(outputs []types.SiacoinOutput) ([]types.Transaction, error)
}

SiacoinSenderMulti is the minimal interface for an object that can send money to multiple siacoin outputs at once.

type SiafundOutputDiff

type SiafundOutputDiff struct {
	Direction     DiffDirection
	ID            types.SiafundOutputID
	SiafundOutput types.SiafundOutput
	ClaimStart    types.Currency
}

A SiafundOutputDiff indicates the addition or removal of a SiafundOutput in the consensus set.

func (*SiafundOutputDiff) DecodeFrom

func (sfd *SiafundOutputDiff) DecodeFrom(d *types.Decoder)

DecodeFrom implements types.DecoderFrom.

func (*SiafundOutputDiff) EncodeTo

func (sfd *SiafundOutputDiff) EncodeTo(e *types.Encoder)

EncodeTo implements types.EncoderTo.

type SiafundPoolDiff

type SiafundPoolDiff struct {
	Direction DiffDirection
	Previous  types.Currency
	Adjusted  types.Currency
}

A SiafundPoolDiff contains the value of the siafundPool before the block was applied, and after the block was applied. When applying the diff, set siafundPool to 'Adjusted'. When reverting the diff, set siafundPool to 'Previous'.

func (*SiafundPoolDiff) DecodeFrom

func (spd *SiafundPoolDiff) DecodeFrom(d *types.Decoder)

DecodeFrom implements types.DecoderFrom.

func (*SiafundPoolDiff) EncodeTo

func (spd *SiafundPoolDiff) EncodeTo(e *types.Encoder)

EncodeTo implements types.EncoderTo.

type Slab

type Slab struct {
	Key       types.Hash256 `json:"key"`
	MinShards uint8         `json:"minShards"`
	Offset    uint64        `json:"offset"`
	Length    uint64        `json:"length"`
	Shards    []Shard       `json:"shards"`
}

Slab is a collection of shards.

func (*Slab) DecodeFrom

func (s *Slab) DecodeFrom(d *types.Decoder)

DecodeFrom implements types.ProtocolObject.

func (*Slab) EncodeTo

func (s *Slab) EncodeTo(e *types.Encoder)

EncodeTo implements types.ProtocolObject.

type SpendingDetails

type SpendingDetails struct {
	DownloadSpending    types.Currency
	FundAccountSpending types.Currency
	MaintenanceSpending MaintenanceSpending
	StorageSpending     types.Currency
	UploadSpending      types.Currency
}

SpendingDetails is a helper struct that contains a breakdown of where exactly the money was spent. The MaintenanceSpending field is an aggregate of costs spent on RHP3 maintenance, this includes updating the price table, syncing the account balance, etc.

type Target

type Target types.Hash256

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.

func RatToTarget

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

RatToTarget converts a big.Rat to a Target.

func (Target) AddDifficulties

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

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

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

func (Target) Cmp

func (x Target) Cmp(y Target) int

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

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

func (Target) Difficulty

func (x Target) Difficulty() types.Currency

Difficulty returns the difficulty associated with a given target.

func (Target) Int

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

Int converts a Target to a big.Int.

func (Target) Inverse

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

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

func (Target) MulDifficulty

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

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

func (Target) Rat

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

Rat converts a Target to a big.Rat.

func (Target) SubtractDifficulties

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

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

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

type TransactionBuilder

type TransactionBuilder interface {
	// FundTransaction adds siacoin inputs worth at least the requested
	// amount to the provided transaction. A change output is also added,
	// if necessary. The inputs will not be available to future calls to
	// FundTransaction unless ReleaseInputs is called.
	FundTransaction(txn *types.Transaction, amount types.Currency) (types.Transaction, []types.Hash256, error)

	// MarkWalletInputs scans a transaction and infers which inputs belong
	// to this wallet. This allows those inputs to be signed.
	MarkWalletInputs(txn types.Transaction) []types.Hash256

	// ReleaseInputs is a helper function that releases the inputs of txn
	// for use in other transactions. It should only be called on
	// transactions that are invalid or will never be broadcast.
	ReleaseInputs(txnSet []types.Transaction)

	// Sign will sign any inputs added by FundTransaction.
	Sign(txn *types.Transaction, toSign []types.Hash256, cf types.CoveredFields) error
}

TransactionBuilder is used to construct transactions.

type TransactionPool

type TransactionPool interface {
	Alerter

	// AcceptTransactionSet accepts a set of potentially interdependent
	// transactions.
	AcceptTransactionSet([]types.Transaction) error

	// Broadcast broadcasts a transaction set to all of the transaction pool's
	// peers.
	Broadcast(ts []types.Transaction)

	// Close is necessary for clean shutdown (e.g. during testing).
	Close() error

	// FeeEstimation returns an estimation for how high the transaction fee
	// needs to be per byte. The minimum recommended targets getting accepted
	// in ~3 blocks, and the maximum recommended targets getting accepted
	// immediately. Taking the average has a moderate chance of being accepted
	// within one block. The minimum has a strong chance of getting accepted
	// within 10 blocks.
	FeeEstimation() (minimumRecommended, maximumRecommended types.Currency)

	// Transaction returns the transaction and unconfirmed parents
	// corresponding to the provided transaction id.
	Transaction(id types.TransactionID) (txn types.Transaction, unconfirmedParents []types.Transaction, exists bool)

	// Transactions returns the transactions of the transaction pool.
	Transactions() []types.Transaction

	// TransactionConfirmed returns true if the transaction has been seen on the
	// blockchain. Note, however, that the block containing the transaction may
	// later be invalidated by a reorg.
	TransactionConfirmed(id types.TransactionID) (bool, error)

	// TransactionList returns a list of all transactions in the transaction
	// pool. The transactions are provided in an order that can acceptably be
	// put into a block.
	TransactionList() []types.Transaction

	// TransactionPoolSubscribe adds a subscriber to the transaction pool.
	// Subscribers will receive all consensus set changes as well as
	// transaction pool changes, and should not subscribe to both.
	TransactionPoolSubscribe(TransactionPoolSubscriber)

	// TransactionSet returns the transaction set the provided object
	// appears in.
	TransactionSet(types.Hash256) []types.Transaction

	// Unsubscribe removes a subscriber from the transaction pool.
	Unsubscribe(TransactionPoolSubscriber)
}

A TransactionPool manages unconfirmed transactions.

type TransactionPoolDiff

type TransactionPoolDiff struct {
	AppliedTransactions  []*UnconfirmedTransactionSet
	RevertedTransactions []TransactionSetID
}

A TransactionPoolDiff indicates the adding or removal of a transaction set to the transaction pool. The transactions in the pool are not persisted, so at startup modules should assume an empty transaction pool.

type TransactionPoolSubscriber

type TransactionPoolSubscriber interface {
	// ReceiveTransactionPoolUpdate notifies subscribers of a change to the
	// consensus set and/or unconfirmed set, and includes the consensus change
	// that would result if all of the transactions made it into a block.
	ReceiveUpdatedUnconfirmedTransactions(*TransactionPoolDiff)
}

A TransactionPoolSubscriber receives updates about the confirmed and unconfirmed set from the transaction pool. Generally, there is no need to subscribe to both the consensus set and the transaction pool.

type TransactionSetID

type TransactionSetID types.Hash256

TransactionSetID is a type-safe wrapper for a types.Hash256 that represents the ID of an entire transaction set.

type UnconfirmedTransactionSet

type UnconfirmedTransactionSet struct {
	Change *ConsensusChange
	ID     TransactionSetID

	IDs          []types.TransactionID
	Sizes        []uint64
	Transactions []types.Transaction
}

UnconfirmedTransactionSet defines a new unconfirmed transaction that has been added to the transaction pool. ID is the ID of the set, IDs contains an ID for each transaction, eliminating the need to recompute it (because that's an expensive operation).

type UnspentOutput

type UnspentOutput struct {
	ID                 types.Hash256   `json:"id"`
	FundType           types.Specifier `json:"fundtype"`
	UnlockHash         types.Address   `json:"unlockhash"`
	Value              types.Currency  `json:"value"`
	ConfirmationHeight uint64          `json:"confirmationheight"`
	IsWatchOnly        bool            `json:"iswatchonly"`
}

A UnspentOutput is a SiacoinOutput or SiafundOutput that the wallet is tracking.

type UserBalance

type UserBalance struct {
	IsUser     bool    `json:"isuser"`
	Subscribed bool    `json:"subscribed"`
	Balance    float64 `json:"balance"`
	Locked     float64 `json:"locked"`
	Currency   string  `json:"currency"`
	SCRate     float64 `json:"scrate"`
	StripeID   string  `json:"stripeid"`
}

UserBalance holds the current balance as well as the data on the chosen payment scheme.

type UserSpendings

type UserSpendings struct {
	CurrentLocked         float64 `json:"currentlocked"`
	CurrentUsed           float64 `json:"currentused"`
	CurrentOverhead       float64 `json:"currentoverhead"`
	PrevLocked            float64 `json:"prevlocked"`
	PrevUsed              float64 `json:"prevused"`
	PrevOverhead          float64 `json:"prevoverhead"`
	SCRate                float64 `json:"scrate"`
	CurrentFormed         uint64  `json:"currentformed"`
	CurrentRenewed        uint64  `json:"currentrenewed"`
	CurrentSlabsSaved     uint64  `json:"currentslabssaved"`
	CurrentSlabsRetrieved uint64  `json:"currentslabsretrieved"`
	CurrentSlabsMigrated  uint64  `json:"currentslabsmigrated"`
	PrevFormed            uint64  `json:"prevformed"`
	PrevRenewed           uint64  `json:"prevrenewed"`
	PrevSlabsSaved        uint64  `json:"prevslabssaved"`
	PrevSlabsRetrieved    uint64  `json:"prevslabsretrieved"`
	PrevSlabsMigrated     uint64  `json:"prevslabsmigrated"`
}

UserSpendings contains the spendings in the current and the previous months.

type ValuedTransaction

type ValuedTransaction struct {
	ProcessedTransaction

	ConfirmedIncomingValue types.Currency `json:"confirmedincomingvalue"`
	ConfirmedOutgoingValue types.Currency `json:"confirmedoutgoingvalue"`
}

ValuedTransaction is a transaction that has been given incoming and outgoing siacoin value fields.

type Wallet

type Wallet interface {
	Alerter
	EncryptionManager
	KeyManager
	TransactionBuilder

	// AddUnlockConditions adds a set of UnlockConditions to the wallet database.
	AddUnlockConditions(uc types.UnlockConditions) error

	// AddWatchAddresses instructs the wallet to begin tracking a set of
	// addresses, in addition to the addresses it was previously tracking.
	// If none of the addresses have appeared in the blockchain, the
	// unused flag may be set to true. Otherwise, the wallet must rescan
	// the blockchain to search for transactions containing the addresses.
	AddWatchAddresses(addrs []types.Address, unused bool) error

	// Close permits clean shutdown during testing and serving.
	Close() error

	// ConfirmedBalance returns the confirmed balance of the wallet, minus
	// any outgoing transactions. ConfirmedBalance will include unconfirmed
	// refund transactions.
	ConfirmedBalance() (siacoinBalance types.Currency, siafundBalance uint64, siacoinClaimBalance types.Currency, err error)

	// UnconfirmedBalance returns the unconfirmed balance of the wallet.
	// Outgoing funds and incoming funds are reported separately. Refund
	// outputs are included, meaning that sending a single coin to
	// someone could result in 'outgoing: 12, incoming: 11'. Siafunds are
	// not considered in the unconfirmed balance.
	UnconfirmedBalance() (outgoingSiacoins types.Currency, incomingSiacoins types.Currency, err error)

	// Height returns the wallet's internal processed consensus height.
	Height() (uint64, error)

	// AddressTransactions returns all of the transactions that are related
	// to a given address.
	AddressTransactions(types.Address) ([]ProcessedTransaction, error)

	// AddressUnconfirmedHistory returns all of the unconfirmed
	// transactions related to a given address.
	AddressUnconfirmedTransactions(types.Address) ([]ProcessedTransaction, error)

	// Transaction returns the transaction with the given id. The bool
	// indicates whether the transaction is in the wallet database. The
	// wallet only stores transactions that are related to the wallet.
	Transaction(types.TransactionID) (ProcessedTransaction, bool, error)

	// Transactions returns all of the transactions that were confirmed at
	// heights [startHeight, endHeight]. Unconfirmed transactions are not
	// included.
	Transactions(startHeight uint64, endHeight uint64) ([]ProcessedTransaction, error)

	// UnconfirmedTransactions returns all unconfirmed transactions
	// relative to the wallet.
	UnconfirmedTransactions() ([]ProcessedTransaction, error)

	// RemoveWatchAddresses instructs the wallet to stop tracking a set of
	// addresses and delete their associated transactions. If none of the
	// addresses have appeared in the blockchain, the unused flag may be
	// set to true. Otherwise, the wallet must rescan the blockchain to
	// rebuild its transaction history.
	RemoveWatchAddresses(addrs []types.Address, unused bool) error

	// Rescanning reports whether the wallet is currently rescanning the
	// blockchain.
	Rescanning() (bool, error)

	// Settings returns the Wallet's current settings.
	Settings() (WalletSettings, error)

	// SetSettings sets the Wallet's settings.
	SetSettings(WalletSettings) error

	// SendSiacoins is a tool for sending Siacoins from the wallet to an
	// address. Sending money usually results in multiple transactions. The
	// transactions are automatically given to the transaction pool, and are
	// also returned to the caller.
	SendSiacoins(amount types.Currency, dest types.Address) ([]types.Transaction, error)

	// SendSiacoinsFeeIncluded sends Siacoins with fees included.
	SendSiacoinsFeeIncluded(amount types.Currency, dest types.Address) ([]types.Transaction, error)

	SiacoinSenderMulti

	// DustThreshold returns the quantity per byte below which a Currency is
	// considered to be Dust.
	DustThreshold() (types.Currency, error)

	// UnspentOutputs returns the unspent outputs tracked by the wallet.
	UnspentOutputs() ([]UnspentOutput, error)

	// UnlockConditions returns the UnlockConditions for the specified
	// address, if they are known to the wallet.
	UnlockConditions(addr types.Address) (types.UnlockConditions, error)

	// WatchAddresses returns the set of addresses that the wallet is
	// currently watching.
	WatchAddresses() ([]types.Address, error)
}

Wallet stores and manages Siacoins and Siafunds. The wallet file is encrypted using a user-specified password. Common addresses are all derived from a single address seed.

type WalletKey

type WalletKey []byte

WalletKey is the key used to encrypt the wallet.

type WalletSettings

type WalletSettings struct {
	NoDefrag bool `json:"nodefrag"`
}

WalletSettings control the behavior of the Wallet.

type WalletTransactionID

type WalletTransactionID types.Hash256

WalletTransactionID is a unique identifier for a wallet transaction.

func CalculateWalletTransactionID

func CalculateWalletTransactionID(tid types.TransactionID, oid types.Hash256) WalletTransactionID

CalculateWalletTransactionID is a helper function for determining the id of a wallet transaction.

Directories

Path Synopsis
hostdb
Package hostdb provides a HostDB object that implements the Manager.HostDB interface.
Package hostdb provides a HostDB object that implements the Manager.HostDB interface.

Jump to

Keyboard shortcuts

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