本文整理匯總了Golang中github.com/NebulousLabs/Sia/types.Currency.Add方法的典型用法代碼示例。如果您正苦於以下問題:Golang Currency.Add方法的具體用法?Golang Currency.Add怎麽用?Golang Currency.Add使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類github.com/NebulousLabs/Sia/types.Currency
的用法示例。
在下文中一共展示了Currency.Add方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: Info
// Info returns generic information about the renter and the files that are
// being rented.
func (r *Renter) Info() (ri modules.RentInfo) {
lockID := r.mu.RLock()
// Include the list of files the renter knows about.
for filename := range r.files {
ri.Files = append(ri.Files, filename)
}
r.mu.RUnlock(lockID)
// Calculate the average cost of a file.
var totalPrice types.Currency
sampleSize := defaultParityPieces + defaultDataPieces
hosts := r.hostDB.RandomHosts(sampleSize)
for _, host := range hosts {
totalPrice = totalPrice.Add(host.Price)
}
if len(hosts) == 0 {
return
}
averagePrice := totalPrice.Div(types.NewCurrency64(uint64(len(hosts))))
estimatedCost := averagePrice.Mul(types.NewCurrency64(defaultDuration)).Mul(types.NewCurrency64(1e9)).Mul(types.NewCurrency64(defaultParityPieces + defaultDataPieces))
// this also accounts for the buffering in the contract negotiation
bufferedCost := estimatedCost.Mul(types.NewCurrency64(5)).Div(types.NewCurrency64(2))
ri.Price = bufferedCost
// Report the number of known hosts.
ri.KnownHosts = len(r.hostDB.ActiveHosts())
return
}
示例2: checkWalletBalance
// checkWalletBalance looks at an upload and determines if there is enough
// money in the wallet to support such an upload. An error is returned if it is
// determined that there is not enough money.
func (r *Renter) checkWalletBalance(up modules.FileUploadParams) error {
// Get the size of the file.
fileInfo, err := os.Stat(up.Filename)
if err != nil {
return err
}
curSize := types.NewCurrency64(uint64(fileInfo.Size()))
var averagePrice types.Currency
sampleSize := up.ErasureCode.NumPieces() * 3 / 2
hosts := r.hostDB.RandomHosts(sampleSize)
for _, host := range hosts {
averagePrice = averagePrice.Add(host.Price)
}
if len(hosts) == 0 {
return errors.New("no hosts!")
}
averagePrice = averagePrice.Div(types.NewCurrency64(uint64(len(hosts))))
estimatedCost := averagePrice.Mul(types.NewCurrency64(uint64(up.Duration))).Mul(curSize)
bufferedCost := estimatedCost.Mul(types.NewCurrency64(2))
siacoinBalance, _, _ := r.wallet.ConfirmedBalance()
if bufferedCost.Cmp(siacoinBalance) > 0 {
return errors.New("insufficient balance for upload")
}
return nil
}
示例3: maxSectors
// maxSectors is the estimated maximum number of sectors that the allowance
// can support.
func maxSectors(a modules.Allowance, hdb hostDB) (uint64, error) {
if a.Hosts == 0 || a.Period == 0 {
return 0, errors.New("invalid allowance")
}
// Sample at least 10 hosts.
nRandomHosts := int(a.Hosts)
if nRandomHosts < 10 {
nRandomHosts = 10
}
hosts := hdb.RandomHosts(nRandomHosts, nil)
if len(hosts) < int(a.Hosts) {
return 0, errors.New("not enough hosts")
}
// Calculate cost of storing 1 sector per host for the allowance period.
var sum types.Currency
for _, h := range hosts {
sum = sum.Add(h.StoragePrice)
}
averagePrice := sum.Div64(uint64(len(hosts)))
costPerSector := averagePrice.Mul64(a.Hosts).Mul64(modules.SectorSize).Mul64(uint64(a.Period))
// Divide total funds by cost per sector.
numSectors, err := a.Funds.Div(costPerSector).Uint64()
if err != nil {
// if there was an overflow, something is definitely wrong
return 0, errors.New("allowance can fund suspiciously large number of sectors")
}
return numSectors, nil
}
示例4: checkSiacoins
// checkSiacoins counts the number of siacoins in the database and verifies
// that it matches the sum of all the coinbases.
func (cs *ConsensusSet) checkSiacoins() error {
// Calculate the number of expected coins in constant time.
deflationBlocks := types.InitialCoinbase - types.MinimumCoinbase
expectedSiacoins := types.CalculateCoinbase(0).Add(types.CalculateCoinbase(cs.height())).Div(types.NewCurrency64(2))
if cs.height() < types.BlockHeight(deflationBlocks) {
expectedSiacoins = expectedSiacoins.Mul(types.NewCurrency64(uint64(cs.height()) + 1))
} else {
expectedSiacoins = expectedSiacoins.Mul(types.NewCurrency64(deflationBlocks + 1))
trailingSiacoins := types.NewCurrency64(uint64(cs.height()) - deflationBlocks).Mul(types.CalculateCoinbase(cs.height()))
expectedSiacoins = expectedSiacoins.Add(trailingSiacoins)
}
totalSiacoins := types.ZeroCurrency
cs.db.forEachSiacoinOutputs(func(scoid types.SiacoinOutputID, sco types.SiacoinOutput) {
totalSiacoins = totalSiacoins.Add(sco.Value)
})
cs.db.forEachFileContracts(func(fcid types.FileContractID, fc types.FileContract) {
var payout types.Currency
for _, output := range fc.ValidProofOutputs {
payout = payout.Add(output.Value)
}
totalSiacoins = totalSiacoins.Add(payout)
})
cs.db.forEachDelayedSiacoinOutputs(func(v types.SiacoinOutputID, dso types.SiacoinOutput) {
totalSiacoins = totalSiacoins.Add(dso.Value)
})
cs.db.forEachSiafundOutputs(func(sfoid types.SiafundOutputID, sfo types.SiafundOutput) {
sfoSiacoins := cs.siafundPool.Sub(sfo.ClaimStart).Div(types.SiafundCount).Mul(sfo.Value)
totalSiacoins = totalSiacoins.Add(sfoSiacoins)
})
if expectedSiacoins.Cmp(totalSiacoins) != 0 {
return errSiacoinMiscount
}
return nil
}
示例5: validUnconfirmedSiafunds
// validUnconfirmedSiafunds checks that all siafund inputs and outputs are
// valid within the context of the unconfirmed consensus set.
func (tp *TransactionPool) validUnconfirmedSiafunds(t types.Transaction) (err error) {
var inputSum types.Currency
for _, sfi := range t.SiafundInputs {
// Check that the corresponding siafund output being spent exists.
sfo, exists := tp.siafundOutputs[sfi.ParentID]
if !exists {
return errors.New("transaction spends unrecognized siafund output")
}
// Check that the unlock conditions match the unlock hash of the
// corresponding output.
if sfi.UnlockConditions.UnlockHash() != sfo.UnlockHash {
return errors.New("transaction contains invalid unlock conditions (hash mismatch)")
}
// Add this input's value to the inputSum.
inputSum = inputSum.Add(sfo.Value)
}
// Check that the value of the outputs equal the value of the inputs.
var outputSum types.Currency
for _, sfo := range t.SiafundOutputs {
outputSum = outputSum.Add(sfo.Value)
}
if outputSum.Cmp(inputSum) != 0 {
return errors.New("siafund inputs do not equal siafund outputs")
}
return
}
示例6: checkMinerFees
// checkMinerFees checks that the total amount of transaction fees in the
// transaction set is sufficient to earn a spot in the transaction pool.
func (tp *TransactionPool) checkMinerFees(ts []types.Transaction) error {
// Transactions cannot be added after the TransactionPoolSizeLimit has been
// hit.
if tp.transactionListSize > TransactionPoolSizeLimit {
return errFullTransactionPool
}
// The first TransactionPoolSizeForFee transactions do not need fees.
if tp.transactionListSize > TransactionPoolSizeForFee {
// Currently required fees are set on a per-transaction basis. 2 coins
// are required per transaction if the free-fee limit has been reached,
// adding a larger fee is not useful.
var feeSum types.Currency
for i := range ts {
for _, fee := range ts[i].MinerFees {
feeSum = feeSum.Add(fee)
}
}
feeRequired := TransactionMinFee.Mul(types.NewCurrency64(uint64(len(ts))))
if feeSum.Cmp(feeRequired) < 0 {
return errLowMinerFees
}
}
return nil
}
示例7: Info
// Info returns generic information about the renter and the files that are
// being rented.
func (r *Renter) Info() (ri modules.RentInfo) {
lockID := r.mu.RLock()
defer r.mu.RUnlock(lockID)
// Include the list of files the renter knows about.
for filename := range r.files {
ri.Files = append(ri.Files, filename)
}
// Calculate the average cost of a file.
var totalPrice types.Currency
redundancy := 6 // reasonable estimate until we come up with an alternative
sampleSize := redundancy * 3 / 2
hosts := r.hostDB.RandomHosts(sampleSize)
for _, host := range hosts {
totalPrice = totalPrice.Add(host.Price)
}
if len(hosts) == 0 {
return
}
averagePrice := totalPrice.Mul(types.NewCurrency64(2)).Div(types.NewCurrency64(3))
// HACK: 6000 is the duration (set by the API), and 1024^3 is a GB. Price
// is reported as per GB, no timeframe is given.
estimatedCost := averagePrice.Mul(types.NewCurrency64(6000)).Mul(types.NewCurrency64(1024 * 1024 * 1024))
bufferedCost := estimatedCost.Mul(types.NewCurrency64(4)).Div(types.NewCurrency64(3))
ri.Price = bufferedCost
// Report the number of known hosts.
ri.KnownHosts = len(r.hostDB.ActiveHosts())
return
}
示例8: validSiafunds
// validSiafunds checks that the siafund portions of the transaction are valid
// in the context of the consensus set.
func (cs *ConsensusSet) validSiafunds(t types.Transaction) (err error) {
// Compare the number of input siafunds to the output siafunds.
var siafundInputSum types.Currency
var siafundOutputSum types.Currency
for _, sfi := range t.SiafundInputs {
exists := cs.db.inSiafundOutputs(sfi.ParentID)
if !exists {
return ErrMissingSiafundOutput
}
sfo := cs.db.getSiafundOutputs(sfi.ParentID)
// Check the unlock conditions match the unlock hash.
if sfi.UnlockConditions.UnlockHash() != sfo.UnlockHash {
return ErrWrongUnlockConditions
}
siafundInputSum = siafundInputSum.Add(sfo.Value)
}
for _, sfo := range t.SiafundOutputs {
siafundOutputSum = siafundOutputSum.Add(sfo.Value)
}
if siafundOutputSum.Cmp(siafundInputSum) != 0 {
return ErrSiafundInputOutputMismatch
}
return
}
示例9: SendSiacoins
// SendSiacoins creates a transaction sending 'amount' to 'dest'. The transaction
// is submitted to the transaction pool and is also returned.
func (w *Wallet) SendSiacoins(amount types.Currency, dest types.UnlockHash) ([]types.Transaction, error) {
if err := w.tg.Add(); err != nil {
return nil, err
}
defer w.tg.Done()
tpoolFee := types.SiacoinPrecision.Mul64(10) // TODO: better fee algo.
output := types.SiacoinOutput{
Value: amount,
UnlockHash: dest,
}
txnBuilder := w.StartTransaction()
err := txnBuilder.FundSiacoins(amount.Add(tpoolFee))
if err != nil {
return nil, err
}
txnBuilder.AddMinerFee(tpoolFee)
txnBuilder.AddSiacoinOutput(output)
txnSet, err := txnBuilder.Sign(true)
if err != nil {
return nil, err
}
err = w.tpool.AcceptTransactionSet(txnSet)
if err != nil {
return nil, err
}
return txnSet, nil
}
示例10: validSiacoins
// validSiacoins checks that the siacoin inputs and outputs are valid in the
// context of the current consensus set.
func validSiacoins(tx *bolt.Tx, t types.Transaction) error {
scoBucket := tx.Bucket(SiacoinOutputs)
var inputSum types.Currency
for _, sci := range t.SiacoinInputs {
// Check that the input spends an existing output.
scoBytes := scoBucket.Get(sci.ParentID[:])
if scoBytes == nil {
return errMissingSiacoinOutput
}
// Check that the unlock conditions match the required unlock hash.
var sco types.SiacoinOutput
err := encoding.Unmarshal(scoBytes, &sco)
if build.DEBUG && err != nil {
panic(err)
}
if sci.UnlockConditions.UnlockHash() != sco.UnlockHash {
return errWrongUnlockConditions
}
inputSum = inputSum.Add(sco.Value)
}
if inputSum.Cmp(t.SiacoinOutputSum()) != 0 {
return errSiacoinInputOutputMismatch
}
return nil
}
示例11: validSiafunds
// validSiafunds checks that the siafund portions of the transaction are valid
// in the context of the consensus set.
func validSiafunds(tx *bolt.Tx, t types.Transaction) (err error) {
// Compare the number of input siafunds to the output siafunds.
var siafundInputSum types.Currency
var siafundOutputSum types.Currency
for _, sfi := range t.SiafundInputs {
sfo, err := getSiafundOutput(tx, sfi.ParentID)
if err != nil {
return err
}
// Check the unlock conditions match the unlock hash.
if sfi.UnlockConditions.UnlockHash() != sfo.UnlockHash {
return errWrongUnlockConditions
}
siafundInputSum = siafundInputSum.Add(sfo.Value)
}
for _, sfo := range t.SiafundOutputs {
siafundOutputSum = siafundOutputSum.Add(sfo.Value)
}
if siafundOutputSum.Cmp(siafundInputSum) != 0 {
return errSiafundInputOutputMismatch
}
return
}
示例12: wallettransactionscmd
// wallettransactionscmd lists all of the transactions related to the wallet,
// providing a net flow of siacoins and siafunds for each.
func wallettransactionscmd() {
wtg := new(api.WalletTransactionsGET)
err := getAPI("/wallet/transactions?startheight=0&endheight=10000000", wtg)
if err != nil {
fmt.Println("Could not fetch transaction history:", err)
return
}
fmt.Println(" [height] [transaction id] [net siacoins] [net siafunds]")
txns := append(wtg.ConfirmedTransactions, wtg.UnconfirmedTransactions...)
for _, txn := range txns {
// Determine the number of outgoing siacoins and siafunds.
var outgoingSiacoins types.Currency
var outgoingSiafunds types.Currency
for _, input := range txn.Inputs {
if input.FundType == types.SpecifierSiacoinInput && input.WalletAddress {
outgoingSiacoins = outgoingSiacoins.Add(input.Value)
}
if input.FundType == types.SpecifierSiafundInput && input.WalletAddress {
outgoingSiafunds = outgoingSiafunds.Add(input.Value)
}
}
// Determine the number of incoming siacoins and siafunds.
var incomingSiacoins types.Currency
var incomingSiafunds types.Currency
for _, output := range txn.Outputs {
if output.FundType == types.SpecifierMinerPayout {
incomingSiacoins = incomingSiacoins.Add(output.Value)
}
if output.FundType == types.SpecifierSiacoinOutput && output.WalletAddress {
incomingSiacoins = incomingSiacoins.Add(output.Value)
}
if output.FundType == types.SpecifierSiafundOutput && output.WalletAddress {
incomingSiafunds = incomingSiafunds.Add(output.Value)
}
}
// Convert the siacoins to a float.
incomingSiacoinsFloat, _ := new(big.Rat).SetFrac(incomingSiacoins.Big(), types.SiacoinPrecision.Big()).Float64()
outgoingSiacoinsFloat, _ := new(big.Rat).SetFrac(outgoingSiacoins.Big(), types.SiacoinPrecision.Big()).Float64()
// Print the results.
if txn.ConfirmationHeight < 1e9 {
fmt.Printf("%12v", txn.ConfirmationHeight)
} else {
fmt.Printf(" unconfirmed")
}
fmt.Printf("%67v%15.2f SC", txn.TransactionID, incomingSiacoinsFloat-outgoingSiacoinsFloat)
// For siafunds, need to avoid having a negative types.Currency.
if incomingSiafunds.Cmp(outgoingSiafunds) >= 0 {
fmt.Printf("%14v SF\n", incomingSiafunds.Sub(outgoingSiafunds))
} else {
fmt.Printf("-%14v SF\n", outgoingSiafunds.Sub(incomingSiafunds))
}
}
}
示例13: CalculateFee
// CalculateFee returns the fee-per-byte of a transaction set.
func CalculateFee(ts []types.Transaction) types.Currency {
var sum types.Currency
for _, t := range ts {
for _, fee := range t.MinerFees {
sum = sum.Add(fee)
}
}
size := len(encoding.Marshal(ts))
return sum.Div64(uint64(size))
}
示例14: checkMinerPayouts
// checkMinerPayouts compares a block's miner payouts to the block's subsidy and
// returns true if they are equal.
func checkMinerPayouts(b types.Block, height types.BlockHeight) bool {
// Add up the payouts and check that all values are legal.
var payoutSum types.Currency
for _, payout := range b.MinerPayouts {
if payout.Value.IsZero() {
return false
}
payoutSum = payoutSum.Add(payout.Value)
}
return b.CalculateSubsidy(height).Cmp(payoutSum) == 0
}
示例15: AveragePrice
// AveragePrice returns the average price of a host.
func (hdb *HostDB) AveragePrice() types.Currency {
// maybe a more sophisticated way of doing this
var totalPrice types.Currency
sampleSize := 18
hosts := hdb.randomHosts(sampleSize, nil)
if len(hosts) == 0 {
return totalPrice
}
for _, host := range hosts {
totalPrice = totalPrice.Add(host.Price)
}
return totalPrice.Div(types.NewCurrency64(uint64(len(hosts))))
}