本文整理汇总了Golang中math/big.NewInt函数的典型用法代码示例。如果您正苦于以下问题:Golang NewInt函数的具体用法?Golang NewInt怎么用?Golang NewInt使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewInt函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: lowestPrice
// returns the lowers possible price with which a tx was or could have been included
func (self *GasPriceOracle) lowestPrice(block *types.Block) *big.Int {
gasUsed := big.NewInt(0)
receipts := core.GetBlockReceipts(self.eth.ChainDb(), block.Hash())
if len(receipts) > 0 {
if cgu := receipts[len(receipts)-1].CumulativeGasUsed; cgu != nil {
gasUsed = receipts[len(receipts)-1].CumulativeGasUsed
}
}
if new(big.Int).Mul(gasUsed, big.NewInt(100)).Cmp(new(big.Int).Mul(block.GasLimit(),
big.NewInt(int64(self.eth.GpoFullBlockRatio)))) < 0 {
// block is not full, could have posted a tx with MinGasPrice
return big.NewInt(0)
}
txs := block.Transactions()
if len(txs) == 0 {
return big.NewInt(0)
}
// block is full, find smallest gasPrice
minPrice := txs[0].GasPrice()
for i := 1; i < len(txs); i++ {
price := txs[i].GasPrice()
if price.Cmp(minPrice) < 0 {
minPrice = price
}
}
return minPrice
}
示例2: factorial
func factorial(x *big.Int) *big.Int {
n := big.NewInt(1)
if x.Cmp(big.NewInt(0)) == 0 {
return n
}
return n.Mul(x, factorial(n.Sub(x, n)))
}
示例3: Interpolate
// Lagrangian interpolation to reconstruct the constant factor for a polynomial
func Interpolate(shares *[]int64, shareAvailable *[]bool, nshare int32, prime *big.Int) int64 {
primebig := big.NewInt(0)
primebig.Set(prime)
resultbig := big.NewInt(0)
for share := int32(0); share < nshare; share++ {
if (*shareAvailable)[share] {
numerator := big.NewInt(1)
denominator := big.NewInt(1)
for otherShare := int32(0); otherShare < nshare; otherShare++ {
if (otherShare == share) || (!(*shareAvailable)[otherShare]) {
continue
}
numerator.Mul(numerator, big.NewInt(-1*int64(otherShare+2)))
denominator.Mul(denominator, big.NewInt(int64(share-otherShare)))
}
lagrange := big.NewInt(1)
lagrange.DivMod(numerator, denominator, primebig)
primebig.Set(prime) // Strangely divmod sets primebig to 0, divmod bad
tmp := big.NewInt(1)
tmp.Mul(big.NewInt((*shares)[share]), lagrange)
resultTmp := big.NewInt(0)
resultTmp.Add(tmp, resultbig)
resultbig.Mod(resultTmp, primebig)
}
}
return resultbig.Int64()
}
示例4: TestInvalidTransactions
func TestInvalidTransactions(t *testing.T) {
pool, key := setupTxPool()
tx := transaction(0, big.NewInt(100), key)
if err := pool.Add(tx); err != ErrNonExistentAccount {
t.Error("expected", ErrNonExistentAccount)
}
from, _ := tx.From()
pool.currentState().AddBalance(from, big.NewInt(1))
if err := pool.Add(tx); err != ErrInsufficientFunds {
t.Error("expected", ErrInsufficientFunds)
}
balance := new(big.Int).Add(tx.Value(), new(big.Int).Mul(tx.Gas(), tx.GasPrice()))
pool.currentState().AddBalance(from, balance)
if err := pool.Add(tx); err != ErrIntrinsicGas {
t.Error("expected", ErrIntrinsicGas, "got", err)
}
pool.currentState().SetNonce(from, 1)
pool.currentState().AddBalance(from, big.NewInt(0xffffffffffffff))
tx = transaction(0, big.NewInt(100000), key)
if err := pool.Add(tx); err != ErrNonce {
t.Error("expected", ErrNonce)
}
}
示例5: GetRecordByHashedString
func (table HashTable) GetRecordByHashedString(
input string, hashTTL time.Duration,
) ([]byte, error) {
hash := sha256.Sum256([]byte(
fmt.Sprintf("%s%d", input, table.getTimeHashPart(hashTTL))),
)
hashMaxLength := int64(1)
index := int64(0)
for _, hashByte := range hash {
if hashMaxLength > table.Count {
break
}
hashMaxLength <<= 8
index += hashMaxLength * int64(hashByte)
}
remainder := big.NewInt(0).Mod(
big.NewInt(index), big.NewInt(table.Count),
).Int64()
return table.GetRecord(remainder)
}
示例6: TestTransactionChainFork
func TestTransactionChainFork(t *testing.T) {
pool, key := setupTxPool()
addr := crypto.PubkeyToAddress(key.PublicKey)
resetState := func() {
db, _ := ethdb.NewMemDatabase()
statedb, _ := state.New(common.Hash{}, db)
pool.currentState = func() (*state.StateDB, error) { return statedb, nil }
currentState, _ := pool.currentState()
currentState.AddBalance(addr, big.NewInt(100000000000000))
pool.resetState()
}
resetState()
tx := transaction(0, big.NewInt(100000), key)
if err := pool.add(tx); err != nil {
t.Error("didn't expect error", err)
}
pool.RemoveTransactions([]*types.Transaction{tx})
// reset the pool's internal state
resetState()
if err := pool.add(tx); err != nil {
t.Error("didn't expect error", err)
}
}
示例7: TestRemoveTx
func TestRemoveTx(t *testing.T) {
pool, key := setupTxPool()
tx := transaction(0, big.NewInt(100), key)
from, _ := tx.From()
pool.currentState().AddBalance(from, big.NewInt(1))
pool.queueTx(tx.Hash(), tx)
pool.addTx(tx.Hash(), from, tx)
if len(pool.queue) != 1 {
t.Error("expected queue to be 1, got", len(pool.queue))
}
if len(pool.pending) != 1 {
t.Error("expected txs to be 1, got", len(pool.pending))
}
pool.removeTx(tx.Hash())
if len(pool.queue) > 0 {
t.Error("expected queue to be 0, got", len(pool.queue))
}
if len(pool.pending) > 0 {
t.Error("expected txs to be 0, got", len(pool.pending))
}
}
示例8: plus
func plus(z *big.Int, x *big.Int, y *big.Int) *big.Int {
var lim big.Int
lim.Exp(big.NewInt(2), big.NewInt(256), big.NewInt(0))
z.Add(x, y)
return z.Mod(z, &lim)
}
示例9: NewSRPConnection
func NewSRPConnection(C []byte, P []byte, H hash.Hash) (srp *SRPConnection, err error) {
secretBytes := make([]byte, 32)
_, err = crand.Reader.Read(secretBytes)
if err != nil {
return nil, err
}
secretHex := hex.EncodeToString(secretBytes)
a, ok := big.NewInt(0).SetString(secretHex, 16)
if !ok {
return nil, fmt.Errorf("Could not initialise SRP a")
}
A := big.NewInt(0).Exp(g, a, n)
srp = &SRPConnection{
C: C,
P: P,
H: H,
a: a,
A: A,
}
return srp, nil
}
示例10: Example_usage
// Full STS communication example illustrated with two concurrent Go routines agreeing on a master key.
func Example_usage() {
// STS cyclic group parameters, global for the app (small examples, not secure!)
group := big.NewInt(3910779947)
generator := big.NewInt(1213725007)
// STS encryption parameters
cipher := aes.NewCipher
bits := 128
hash := crypto.SHA1
// RSA key-pairs for the communicating parties, obtained from somewhere else (no error checks)
iniKey, _ := rsa.GenerateKey(rand.Reader, 1024)
accKey, _ := rsa.GenerateKey(rand.Reader, 1024)
// Start two Go routines: one initiator and one acceptor communicating on a channel
transport := make(chan []byte)
iniOut := make(chan []byte)
accOut := make(chan []byte)
go initiator(group, generator, cipher, bits, hash, iniKey, &accKey.PublicKey, transport, iniOut)
go acceptor(group, generator, cipher, bits, hash, accKey, &iniKey.PublicKey, transport, accOut)
// Check that the parties agreed upon the same master key
iniMaster, iniOk := <-iniOut
accMaster, accOk := <-accOut
fmt.Printf("Initiator key valid: %v\n", iniOk && iniMaster != nil)
fmt.Printf("Acceptor key valid: %v\n", accOk && accMaster != nil)
fmt.Printf("Keys match: %v\n", bytes.Equal(iniMaster, accMaster))
// Output:
// Initiator key valid: true
// Acceptor key valid: true
// Keys match: true
}
示例11: exponential
// exponential computes exp(x) using the Taylor series. It converges quickly
// since we call it with only small values of x.
func exponential(x *big.Float) *big.Float {
// The Taylor series for e**x, exp(x), is 1 + x + x²/2! + x³/3! ...
xN := newF().Set(x)
term := newF()
n := big.NewInt(1)
nFactorial := big.NewInt(1)
z := newF().SetInt64(1)
loop := newLoop("exponential", x, 4)
for i := 0; ; i++ {
term.Set(xN)
nf := newF().SetInt(nFactorial)
term.Quo(term, nf)
z.Add(z, term)
if loop.terminate(z) {
break
}
// Advance x**index (multiply by x).
xN.Mul(xN, x)
// Advance n, n!.
n.Add(n, bigOne.Int)
nFactorial.Mul(nFactorial, n)
}
return z
}
示例12: newDSAPublicKeyFromJSON
func newDSAPublicKeyFromJSON(s []byte) (*dsaPublicKey, error) {
dsakey := new(dsaPublicKey)
dsajson := new(dsaPublicKeyJSON)
var err error
err = json.Unmarshal([]byte(s), &dsajson)
if err != nil {
return nil, err
}
if !T_DSA_PUB.isAcceptableSize(dsajson.Size) {
return nil, ErrInvalidKeySize
}
b, err := decodeWeb64String(dsajson.Y)
if err != nil {
return nil, ErrBase64Decoding
}
dsakey.key.Y = big.NewInt(0).SetBytes(b)
b, err = decodeWeb64String(dsajson.G)
if err != nil {
return nil, ErrBase64Decoding
}
dsakey.key.G = big.NewInt(0).SetBytes(b)
b, err = decodeWeb64String(dsajson.P)
if err != nil {
return nil, ErrBase64Decoding
}
dsakey.key.P = big.NewInt(0).SetBytes(b)
b, err = decodeWeb64String(dsajson.Q)
if err != nil {
return nil, ErrBase64Decoding
}
dsakey.key.Q = big.NewInt(0).SetBytes(b)
return dsakey, nil
}
示例13: TestScan
func TestScan(t *testing.T) {
// Define some local constants
over1, _ := net.ResolveTCPAddr("tcp", "127.0.0.3:33333")
over2, _ := net.ResolveTCPAddr("tcp", "127.0.0.5:55555")
ipnet1 := &net.IPNet{
IP: over1.IP,
Mask: over1.IP.DefaultMask(),
}
ipnet2 := &net.IPNet{
IP: over2.IP,
Mask: over2.IP.DefaultMask(),
}
// Start up two bootstrappers
bs1, evs1, err := New(ipnet1, []byte("magic"), big.NewInt(1), over1.Port)
if err != nil {
t.Fatalf("failed to create first booter: %v.", err)
}
if err := bs1.Boot(); err != nil {
t.Fatalf("failed to boot first booter: %v.", err)
}
defer bs1.Terminate()
bs2, evs2, err := New(ipnet2, []byte("magic"), big.NewInt(2), over2.Port)
if err != nil {
t.Fatalf("failed to create second booter: %v.", err)
}
if err := bs2.Boot(); err != nil {
t.Fatalf("failed to boot second booter: %v.", err)
}
defer bs2.Terminate()
// Wait and make sure they found each other and not themselves
e1, e2 := <-evs1, <-evs2
if !e1.Addr.IP.Equal(over2.IP) || e1.Addr.Port != over2.Port {
t.Fatalf("invalid address on first booter: have %v, want %v.", e1.Addr, over2)
}
if !e2.Addr.IP.Equal(over1.IP) || e2.Addr.Port != over1.Port {
t.Fatalf("invalid address on second booter: have %v, want %v.", e2.Addr, over1)
}
// Each should report twice (foreign request + foreign response to local request)
e1, e2 = <-evs1, <-evs2
if !e1.Addr.IP.Equal(over2.IP) || e1.Addr.Port != over2.Port {
t.Fatalf("invalid address on first booter: have %v, want %v.", e1.Addr, over2)
}
if !e2.Addr.IP.Equal(over1.IP) || e2.Addr.Port != over1.Port {
t.Fatalf("invalid address on second booter: have %v, want %v.", e2.Addr, over1)
}
// Further beats shouldn't arrive (unless the probing catches us, should be rare)
timeout := time.Tick(250 * time.Millisecond)
select {
case <-timeout:
// Do nothing
case a := <-evs1:
t.Fatalf("extra address on first booter: %v.", a)
case a := <-evs2:
t.Fatalf("extra address on second booter: %v.", a)
}
}
示例14: init
func init() {
jwk1 = jose.JWK{
ID: "1",
Type: "RSA",
Alg: "RS256",
Use: "sig",
Modulus: big.NewInt(1),
Exponent: 65537,
}
jwk2 = jose.JWK{
ID: "2",
Type: "RSA",
Alg: "RS256",
Use: "sig",
Modulus: big.NewInt(2),
Exponent: 65537,
}
jwk3 = jose.JWK{
ID: "3",
Type: "RSA",
Alg: "RS256",
Use: "sig",
Modulus: big.NewInt(3),
Exponent: 65537,
}
}
示例15: InitDocumentHandler
func InitDocumentHandler(defs UploadDefs) {
// initialize upload handling parameters
uploadPath = defs.Path
treshold = defs.ShareTreshold
// check for disabled secret sharing scheme
if treshold > 0 {
// compute prime: (2^512-1) - SharePrimeOfs
one := big.NewInt(1)
ofs := big.NewInt(int64(defs.SharePrimeOfs))
prime = new(big.Int).Lsh(one, 512)
prime = new(big.Int).Sub(prime, one)
prime = new(big.Int).Sub(prime, ofs)
// open keyring file
rdr, err := os.Open(defs.Keyring)
if err != nil {
// can't read keys -- terminate!
logger.Printf(logger.ERROR, "[sid.upload] Can't read keyring file '%s' -- terminating!\n", defs.Keyring)
os.Exit(1)
}
defer rdr.Close()
// read public keys from keyring
if reviewer, err = openpgp.ReadKeyRing(rdr); err != nil {
// can't read keys -- terminate!
logger.Printf(logger.ERROR, "[sid.upload] Failed to process keyring '%s' -- terminating!\n", defs.Keyring)
os.Exit(1)
}
} else {
logger.Printf(logger.WARN, "[sid.upload] Secret sharing scheme disabled -- uploads will be stored unencrypted!!")
}
}