本文整理匯總了Golang中github.com/NebulousLabs/Sia/types.Currency類的典型用法代碼示例。如果您正苦於以下問題:Golang Currency類的具體用法?Golang Currency怎麽用?Golang Currency使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了Currency類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: newRevision
// newRevision revises the current revision to incorporate new data.
func newRevision(rev types.FileContractRevision, pieceLen uint64, merkleRoot crypto.Hash, piecePrice types.Currency) types.FileContractRevision {
// prevent a negative currency panic
if piecePrice.Cmp(rev.NewValidProofOutputs[0].Value) > 0 {
// probably not enough money, but the host might accept it anyway
piecePrice = rev.NewValidProofOutputs[0].Value
}
return types.FileContractRevision{
ParentID: rev.ParentID,
UnlockConditions: rev.UnlockConditions,
NewRevisionNumber: rev.NewRevisionNumber + 1,
NewFileSize: rev.NewFileSize + pieceLen,
NewFileMerkleRoot: merkleRoot,
NewWindowStart: rev.NewWindowStart,
NewWindowEnd: rev.NewWindowEnd,
NewValidProofOutputs: []types.SiacoinOutput{
// less returned to renter
{Value: rev.NewValidProofOutputs[0].Value.Sub(piecePrice), UnlockHash: rev.NewValidProofOutputs[0].UnlockHash},
// more given to host
{Value: rev.NewValidProofOutputs[1].Value.Add(piecePrice), UnlockHash: rev.NewValidProofOutputs[1].UnlockHash},
},
NewMissedProofOutputs: []types.SiacoinOutput{
// less returned to renter
{Value: rev.NewMissedProofOutputs[0].Value.Sub(piecePrice), UnlockHash: rev.NewMissedProofOutputs[0].UnlockHash},
// more given to void
{Value: rev.NewMissedProofOutputs[1].Value.Add(piecePrice), UnlockHash: rev.NewMissedProofOutputs[1].UnlockHash},
},
NewUnlockHash: rev.NewUnlockHash,
}
}
示例2: 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
}
示例3: 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
}
示例4: 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
}
示例5: findOutputs
// findOutputs returns a set of spendable outputs that add up to at least
// `amount` of coins, returning an error if it cannot. It also returns the
// `total`, which is the sum of all the outputs that were found, since it's
// unlikely that it will equal amount exaclty.
func (w *Wallet) findOutputs(amount types.Currency) (knownOutputs []*knownOutput, total types.Currency, err error) {
if amount.IsZero() {
err = errors.New("cannot fund amount <= 0")
return
}
// Iterate through all outputs until enough coins have been assembled.
for _, key := range w.keys {
if !key.spendable {
continue
}
for _, knownOutput := range key.outputs {
if !knownOutput.spendable {
continue
}
if knownOutput.age > w.age-AgeDelay {
continue
}
total = total.Add(knownOutput.output.Value)
knownOutputs = append(knownOutputs, knownOutput)
if total.Cmp(amount) >= 0 {
return
}
}
}
// This code will only be reached if total < amount, meaning insufficient
// funds.
err = modules.LowBalanceErr
return
}
示例6: 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
}
示例7: 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
}
示例8: 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
}
示例9: 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
}
示例10: TestRPCUpload
// TestRPCUPload attempts to upload a file to the host, adding coverage to the
// upload function.
func TestRPCUpload(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
ht, err := newHostTester("TestRPCUpload")
if err != nil {
t.Fatal(err)
}
ht.host.mu.RLock()
baselineAnticipatedRevenue := ht.host.anticipatedRevenue
baselineSpace := ht.host.spaceRemaining
ht.host.mu.RUnlock()
_, err = ht.uploadFile("TestRPCUpload - 1", renewDisabled)
if err != nil {
t.Fatal(err)
}
var expectedRevenue types.Currency
func() {
ht.host.mu.RLock()
defer ht.host.mu.RUnlock()
if ht.host.anticipatedRevenue.Cmp(baselineAnticipatedRevenue) <= 0 {
t.Error("Anticipated revenue did not increase after a file was uploaded")
}
if baselineSpace <= ht.host.spaceRemaining {
t.Error("space remaining on the host does not seem to have decreased")
}
expectedRevenue = ht.host.anticipatedRevenue
}()
// Mine until the storage proof goes through, and the obligation gets
// cleared.
for i := types.BlockHeight(0); i <= testUploadDuration+confirmationRequirement+defaultWindowSize; i++ {
_, err := ht.miner.AddBlock()
if err != nil {
t.Fatal(err)
}
}
// Check that the storage proof has succeeded.
ht.host.mu.Lock()
defer ht.host.mu.Unlock()
if len(ht.host.obligationsByID) != 0 {
t.Error("host still has obligation, when it should have completed the obligation and submitted a storage proof.")
}
if !ht.host.anticipatedRevenue.IsZero() {
t.Error("host anticipated revenue was not set back to zero")
}
if ht.host.spaceRemaining != baselineSpace {
t.Error("host does not seem to have reclaimed the space after a successful obligation")
}
if expectedRevenue.Cmp(ht.host.revenue) != 0 {
t.Error("host's revenue was not moved from anticipated to expected")
}
}
示例11: 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))
}
示例12: 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
}
示例13: 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))))
}
示例14: currencyUnits
// currencyUnits converts a types.Currency to a string with human-readable
// units. The unit used will be the largest unit that results in a value
// greater than 1. The value is rounded to 4 significant digits.
func currencyUnits(c types.Currency) string {
pico := types.SiacoinPrecision.Div64(1e12)
if c.Cmp(pico) < 0 {
return c.String() + " H"
}
// iterate until we find a unit greater than c
mag := pico
unit := ""
for _, unit = range []string{"pS", "nS", "uS", "mS", "SC", "KS", "MS", "GS", "TS"} {
if c.Cmp(mag.Mul64(1e3)) < 0 {
break
} else if unit != "TS" {
// don't want to perform this multiply on the last iter; that
// would give us 1.235 TS instead of 1235 TS
mag = mag.Mul64(1e3)
}
}
num := new(big.Rat).SetInt(c.Big())
denom := new(big.Rat).SetInt(mag.Big())
res, _ := new(big.Rat).Mul(num, denom.Inv(denom)).Float64()
return fmt.Sprintf("%.4g %s", res, unit)
}
示例15: 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
}