本文整理汇总了Golang中math/big.Int.Add方法的典型用法代码示例。如果您正苦于以下问题:Golang Int.Add方法的具体用法?Golang Int.Add怎么用?Golang Int.Add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类math/big.Int
的用法示例。
在下文中一共展示了Int.Add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: schnorrCombineSigs
// schnorrCombineSigs combines a list of partial Schnorr signatures s values
// into a complete signature s for some group public key. This is achieved
// by simply adding the s values of the partial signatures as scalars.
func schnorrCombineSigs(curve *secp256k1.KoblitzCurve, sigss [][]byte) (*big.Int,
error) {
combinedSigS := new(big.Int).SetInt64(0)
for i, sigs := range sigss {
sigsBI := EncodedBytesToBigInt(copyBytes(sigs))
if sigsBI.Cmp(bigZero) == 0 {
str := fmt.Sprintf("sig s %v is zero", i)
return nil, schnorrError(ErrInputValue, str)
}
if sigsBI.Cmp(curve.N) >= 0 {
str := fmt.Sprintf("sig s %v is out of bounds", i)
return nil, schnorrError(ErrInputValue, str)
}
combinedSigS.Add(combinedSigS, sigsBI)
combinedSigS.Mod(combinedSigS, curve.N)
}
if combinedSigS.Cmp(bigZero) == 0 {
str := fmt.Sprintf("combined sig s %v is zero", combinedSigS)
return nil, schnorrError(ErrZeroSigS, str)
}
return combinedSigS, nil
}
示例2: bigAdd
func bigAdd(IntSlice []big.Int) *big.Int {
var sum *big.Int = big.NewInt(0)
for i := 0; i < len(IntSlice); i++ {
sum.Add(sum, &IntSlice[i])
}
return sum
}
示例3: FromFactorBigInt
/*
FromFactorBigInt returns n such that d | Mn if n <= max and d is odd. In other
cases zero is returned.
It is conjectured that every odd d ∊ N divides infinitely many Mersenne numbers.
The returned n should be the exponent of smallest such Mn.
NOTE: The computation of n from a given d performs roughly in O(n). It is
thus highly recomended to use the 'max' argument to limit the "searched"
exponent upper bound as appropriate. Otherwise the computation can take a long
time as a large factor can be a divisor of a Mn with exponent above the uint32
limits.
The FromFactorBigInt function is a modification of the original Will
Edgington's "reverse method", discussed here:
http://tech.groups.yahoo.com/group/primenumbers/message/15061
*/
func FromFactorBigInt(d *big.Int, max uint32) (n uint32) {
if d.Bit(0) == 0 {
return
}
var m big.Int
for n < max {
m.Add(&m, d)
i := 0
for ; m.Bit(i) == 1; i++ {
if n == math.MaxUint32 {
return 0
}
n++
}
m.Rsh(&m, uint(i))
if m.Sign() == 0 {
if n > max {
n = 0
}
return
}
}
return 0
}
示例4: CalcGasLimit
// CalcGasLimit computes the gas limit of the next block after parent.
// The result may be modified by the caller.
// This is miner strategy, not consensus protocol.
func CalcGasLimit(parent *types.Block) *big.Int {
// contrib = (parentGasUsed * 3 / 2) / 1024
contrib := new(big.Int).Mul(parent.GasUsed(), big.NewInt(3))
contrib = contrib.Div(contrib, big.NewInt(2))
contrib = contrib.Div(contrib, params.GasLimitBoundDivisor)
// decay = parentGasLimit / 1024 -1
decay := new(big.Int).Div(parent.GasLimit(), params.GasLimitBoundDivisor)
decay.Sub(decay, big.NewInt(1))
/*
strategy: gasLimit of block-to-mine is set based on parent's
gasUsed value. if parentGasUsed > parentGasLimit * (2/3) then we
increase it, otherwise lower it (or leave it unchanged if it's right
at that usage) the amount increased/decreased depends on how far away
from parentGasLimit * (2/3) parentGasUsed is.
*/
gl := new(big.Int).Sub(parent.GasLimit(), decay)
gl = gl.Add(gl, contrib)
gl.Set(common.BigMax(gl, params.MinGasLimit))
// however, if we're now below the target (TargetGasLimit) we increase the
// limit as much as we can (parentGasLimit / 1024 -1)
if gl.Cmp(params.TargetGasLimit) < 0 {
gl.Add(parent.GasLimit(), decay)
gl.Set(common.BigMin(gl, params.TargetGasLimit))
}
return gl
}
示例5: SumOfBigInts
func SumOfBigInts(nums []*big.Int) *big.Int {
var sum *big.Int = big.NewInt(0)
for _, i := range nums {
sum.Add(sum, i)
}
return sum
}
示例6: ApplyTransactions
func (self *BlockProcessor) ApplyTransactions(gp GasPool, statedb *state.StateDB, block *types.Block, txs types.Transactions, transientProcess bool) (types.Receipts, error) {
var (
receipts types.Receipts
totalUsedGas = big.NewInt(0)
err error
cumulativeSum = new(big.Int)
header = block.Header()
)
for i, tx := range txs {
statedb.StartRecord(tx.Hash(), block.Hash(), i)
receipt, txGas, err := self.ApplyTransaction(gp, statedb, header, tx, totalUsedGas, transientProcess)
if err != nil {
return nil, err
}
if err != nil {
glog.V(logger.Core).Infoln("TX err:", err)
}
receipts = append(receipts, receipt)
cumulativeSum.Add(cumulativeSum, new(big.Int).Mul(txGas, tx.GasPrice()))
}
if block.GasUsed().Cmp(totalUsedGas) != 0 {
return nil, ValidationError(fmt.Sprintf("gas used error (%v / %v)", block.GasUsed(), totalUsedGas))
}
if transientProcess {
go self.eventMux.Post(PendingBlockEvent{block, statedb.Logs()})
}
return receipts, err
}
示例7: Verify
//Verify verifies the proof file server send.
func (sw *Swizzle) Verify(p Proof) (bool, error) {
proof, ok := p.(*SwizzleProof)
if !ok {
return false, errors.New("use SwizzleProof instance for proof")
}
var rhs big.Int
var dummy big.Int
ch := sw.lastChallenge
for i := 0; i < sw.chunks; i++ {
f, err := keyedPRFBig(sw.fKey, sw.prime, i)
if err != nil {
return false, err
}
v, err := keyedPRFBig(ch.Key, ch.Vmax, i)
if err != nil {
return false, err
}
rhs.Add(&rhs, dummy.Mul(v, f))
}
for j := 0; j < ch.Sectors; j++ {
alpha, err := keyedPRFBig(sw.alphaKey, sw.prime, j)
if err != nil {
return false, err
}
rhs.Add(&rhs, dummy.Mul(alpha, &proof.Mu[j]))
}
dummy.DivMod(&rhs, sw.prime, &rhs)
if proof.Sigma.Cmp(&rhs) == 0 {
return true, nil
}
return false, nil
}
示例8: main
func main() {
var s string
var n, two, tmp big.Int
two.SetInt64(2)
in, _ := os.Open("10519.in")
defer in.Close()
out, _ := os.Create("10519.out")
defer out.Close()
for {
if _, err := fmt.Fscanf(in, "%s", &s); err != nil {
break
}
if s == "0" {
fmt.Fprintln(out, 1)
continue
}
n.SetString(s, 10)
tmp.Mul(&n, &n)
tmp.Sub(&tmp, &n)
tmp.Add(&tmp, &two)
fmt.Fprintln(out, &tmp)
}
}
示例9: PayFee
func (block *Block) PayFee(addr []byte, fee *big.Int) bool {
contract := block.state.GetContract(addr)
// If we can't pay the fee return
if contract == nil || contract.Amount.Cmp(fee) < 0 /* amount < fee */ {
fmt.Println("Contract has insufficient funds", contract.Amount, fee)
return false
}
base := new(big.Int)
contract.Amount = base.Sub(contract.Amount, fee)
block.state.trie.Update(string(addr), string(contract.RlpEncode()))
data := block.state.trie.Get(string(block.Coinbase))
// Get the ether (Coinbase) and add the fee (gief fee to miner)
ether := NewAccountFromData([]byte(data))
base = new(big.Int)
ether.Amount = base.Add(ether.Amount, fee)
block.state.trie.Update(string(block.Coinbase), string(ether.RlpEncode()))
return true
}
示例10: GenerateKey
// GenerateKey generates a public and private key pair using random source rand.
func GenerateKey(rand io.Reader) (priv PrivateKey, err error) {
/* See Certicom's SEC1 3.2.1, pg.23 */
/* See NSA's Suite B Implementer’s Guide to FIPS 186-3 (ECDSA) A.1.1, pg.18 */
/* Select private key d randomly from [1, n) */
/* Read N bit length random bytes + 64 extra bits */
b := make([]byte, secp256k1.N.BitLen()/8+8)
_, err = io.ReadFull(rand, b)
if err != nil {
return priv, fmt.Errorf("Reading random reader: %v", err)
}
d := new(big.Int).SetBytes(b)
/* Mod n-1 to shift d into [0, n-1) range */
d.Mod(d, new(big.Int).Sub(secp256k1.N, big.NewInt(1)))
/* Add one to shift d to [1, n) range */
d.Add(d, big.NewInt(1))
priv.D = d
/* Derive public key from private key */
priv.derive()
return priv, nil
}
示例11: powerOffset
// powerOffset computes the offset by (n + 2^exp) % (2^mod)
func powerOffset(id []byte, exp int, mod int) []byte {
// Copy the existing slice
off := make([]byte, len(id))
copy(off, id)
// Convert the ID to a bigint
idInt := big.Int{}
idInt.SetBytes(id)
// Get the offset
two := big.NewInt(2)
offset := big.Int{}
offset.Exp(two, big.NewInt(int64(exp)), nil)
// Sum
sum := big.Int{}
sum.Add(&idInt, &offset)
// Get the ceiling
ceil := big.Int{}
ceil.Exp(two, big.NewInt(int64(mod)), nil)
// Apply the mod
idInt.Mod(&sum, &ceil)
// Add together
return idInt.Bytes()
}
示例12: calcLastFinger
// (n - 2^(k-1)) mod 2^m
func calcLastFinger(n []byte, k int) (string, []byte) {
// convert the n to a bigint
nBigInt := big.Int{}
nBigInt.SetBytes(n)
// get the right addend, i.e. 2^(k-1)
two := big.NewInt(2)
addend := big.Int{}
addend.Exp(two, big.NewInt(int64(k-1)), nil)
addend.Mul(&addend, big.NewInt(-1))
//Soustraction
neg := big.Int{}
neg.Add(&addend, &nBigInt)
// calculate 2^m
m := 160
ceil := big.Int{}
ceil.Exp(two, big.NewInt(int64(m)), nil)
// apply the mod
result := big.Int{}
result.Mod(&neg, &ceil)
resultBytes := result.Bytes()
resultHex := fmt.Sprintf("%x", resultBytes)
return resultHex, resultBytes
}
示例13: calcFinger
// (n + 2^(k-1)) mod (2^m)
func calcFinger(n []byte, k int, m int) (string, []byte) {
// convert the n to a bigint
nBigInt := big.Int{}
nBigInt.SetBytes(n)
// get the right addend, i.e. 2^(k-1)
two := big.NewInt(2)
addend := big.Int{}
addend.Exp(two, big.NewInt(int64(k-1)), nil)
// calculate sum
sum := big.Int{}
sum.Add(&nBigInt, &addend)
// calculate 2^m
ceil := big.Int{}
ceil.Exp(two, big.NewInt(int64(m)), nil)
// apply the mod
result := big.Int{}
result.Mod(&sum, &ceil)
resultBytes := result.Bytes()
resultHex := fmt.Sprintf("%x", resultBytes)
return resultHex, resultBytes
}
示例14: CalculateBlockReward
func CalculateBlockReward(block *Block, uncleLength int) *big.Int {
base := new(big.Int)
for i := 0; i < uncleLength; i++ {
base.Add(base, UncleInclusionReward)
}
return base.Add(base, BlockReward)
}
示例15: signRFC6979
// signRFC6979 generates a deterministic ECDSA signature according to RFC 6979
// and BIP 62.
func signRFC6979(privateKey *PrivateKey, hash []byte) (*Signature, error) {
privkey := privateKey.ToECDSA()
N := order
k := NonceRFC6979(privkey.D, hash, nil, nil)
inv := new(big.Int).ModInverse(k, N)
r, _ := privkey.Curve.ScalarBaseMult(k.Bytes())
if r.Cmp(N) == 1 {
r.Sub(r, N)
}
if r.Sign() == 0 {
return nil, errors.New("calculated R is zero")
}
e := hashToInt(hash, privkey.Curve)
s := new(big.Int).Mul(privkey.D, r)
s.Add(s, e)
s.Mul(s, inv)
s.Mod(s, N)
if s.Cmp(halforder) == 1 {
s.Sub(N, s)
}
if s.Sign() == 0 {
return nil, errors.New("calculated S is zero")
}
return &Signature{R: r, S: s}, nil
}