本文整理匯總了Golang中math/big.Int.Cmp方法的典型用法代碼示例。如果您正苦於以下問題:Golang Int.Cmp方法的具體用法?Golang Int.Cmp怎麽用?Golang Int.Cmp使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類math/big.Int
的用法示例。
在下文中一共展示了Int.Cmp方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: calcDiffAdjust
/* calcDiff returns a bool given two block headers. This bool is
true if the correct dificulty adjustment is seen in the "next" header.
Only feed it headers n-2016 and n-1, otherwise it will calculate a difficulty
when no adjustment should take place, and return false.
Note that the epoch is actually 2015 blocks long, which is confusing. */
func calcDiffAdjust(start, end wire.BlockHeader, p *chaincfg.Params) uint32 {
duration := end.Timestamp.UnixNano() - start.Timestamp.UnixNano()
if duration < minRetargetTimespan {
log.Printf("whoa there, block %s off-scale high 4X diff adjustment!",
end.BlockSha().String())
duration = minRetargetTimespan
} else if duration > maxRetargetTimespan {
log.Printf("Uh-oh! block %s off-scale low 0.25X diff adjustment!\n",
end.BlockSha().String())
duration = maxRetargetTimespan
}
// calculation of new 32-byte difficulty target
// first turn the previous target into a big int
prevTarget := blockchain.CompactToBig(start.Bits)
// new target is old * duration...
newTarget := new(big.Int).Mul(prevTarget, big.NewInt(duration))
// divided by 2 weeks
newTarget.Div(newTarget, big.NewInt(int64(targetTimespan)))
// clip again if above minimum target (too easy)
if newTarget.Cmp(p.PowLimit) > 0 {
newTarget.Set(p.PowLimit)
}
// calculate and return 4-byte 'bits' difficulty from 32-byte target
return blockchain.BigToCompact(newTarget)
}
示例2: validateECPublicKey
// validateECPublicKey checks that the point is a valid public key for
// the given curve. See [SEC1], 3.2.2
func validateECPublicKey(curve elliptic.Curve, x, y *big.Int) bool {
if x.Sign() == 0 && y.Sign() == 0 {
return false
}
if x.Cmp(curve.Params().P) >= 0 {
return false
}
if y.Cmp(curve.Params().P) >= 0 {
return false
}
if !curve.IsOnCurve(x, y) {
return false
}
// We don't check if N * PubKey == 0, since
//
// - the NIST curves have cofactor = 1, so this is implicit.
// (We don't foresee an implementation that supports non NIST
// curves)
//
// - for ephemeral keys, we don't need to worry about small
// subgroup attacks.
return true
}
示例3: parseECPrivateKey
// parseECPrivateKey parses an ASN.1 Elliptic Curve Private Key Structure.
// The OID for the named curve may be provided from another source (such as
// the PKCS8 container) - if it is provided then use this instead of the OID
// that may exist in the EC private key structure.
func parseECPrivateKey(namedCurveOID *asn1.ObjectIdentifier, der []byte) (key *ecdsa.PrivateKey, err error) {
var privKey ecPrivateKey
if _, err := asn1.Unmarshal(der, &privKey); err != nil {
return nil, errors.New("x509: failed to parse EC private key: " + err.Error())
}
if privKey.Version != ecPrivKeyVersion {
return nil, fmt.Errorf("x509: unknown EC private key version %d", privKey.Version)
}
var curve elliptic.Curve
if namedCurveOID != nil {
curve = namedCurveFromOID(*namedCurveOID)
} else {
curve = namedCurveFromOID(privKey.NamedCurveOID)
}
if curve == nil {
return nil, errors.New("x509: unknown elliptic curve")
}
k := new(big.Int).SetBytes(privKey.PrivateKey)
if k.Cmp(curve.Params().N) >= 0 {
return nil, errors.New("x509: invalid elliptic curve private key value")
}
priv := new(ecdsa.PrivateKey)
priv.Curve = curve
priv.D = k
priv.X, priv.Y = curve.ScalarBaseMult(privKey.PrivateKey)
return priv, nil
}
示例4: Base58Encode
// Base58Encode encodes a byte slice to a modified base58 string.
func Base58Encode(b []byte, alphabet string) string {
x := new(big.Int)
x.SetBytes(b)
answer := make([]byte, 0)
for x.Cmp(bigZero) > 0 {
mod := new(big.Int)
x.DivMod(x, bigRadix, mod)
answer = append(answer, alphabet[mod.Int64()])
}
// leading zero bytes
for _, i := range b {
if i != 0 {
break
}
answer = append(answer, alphabet[0])
}
// reverse
alen := len(answer)
for i := 0; i < alen/2; i++ {
answer[i], answer[alen-1-i] = answer[alen-1-i], answer[i]
}
return string(answer)
}
示例5: BigMax
// Big max
//
// Returns the maximum size big integer
func BigMax(x, y *big.Int) *big.Int {
if x.Cmp(y) < 0 {
return y
}
return x
}
示例6: pubKeyDecrypt
/*公鑰解密*/
func pubKeyDecrypt(pub *rsa.PublicKey, data []byte) ([]byte, error) {
k := (pub.N.BitLen() + 7) / 8
if k != len(data) {
return nil, ErrDataLen
}
m := new(big.Int).SetBytes(data)
if m.Cmp(pub.N) > 0 {
return nil, ErrDataToLarge
}
m.Exp(m, big.NewInt(int64(pub.E)), pub.N)
d := leftPad(m.Bytes(), k)
if d[0] != 0 {
return nil, ErrDataBroken
}
if d[1] != 0 && d[1] != 1 {
return nil, ErrKeyPairDismatch
}
var i = 2
for ; i < len(d); i++ {
if d[i] == 0 {
break
}
}
i++
if i == len(d) {
return nil, nil
}
return d[i:], nil
}
示例7: Validate
// Validate performs basic sanity checks on the key.
// It returns nil if the key is valid, or else an error describing a problem.
func (priv *PrivateKey) Validate() error {
if err := checkPub(&priv.PublicKey); err != nil {
return err
}
// Check that Πprimes == n.
modulus := new(big.Int).Set(bigOne)
for _, prime := range priv.Primes {
modulus.Mul(modulus, prime)
}
if modulus.Cmp(priv.N) != 0 {
return errors.New("crypto/rsa: invalid modulus")
}
// Check that de ≡ 1 mod p-1, for each prime.
// This implies that e is coprime to each p-1 as e has a multiplicative
// inverse. Therefore e is coprime to lcm(p-1,q-1,r-1,...) =
// exponent(ℤ/nℤ). It also implies that a^de ≡ a mod p as a^(p-1) ≡ 1
// mod p. Thus a^de ≡ a mod n for all a coprime to n, as required.
congruence := new(big.Int)
de := new(big.Int).SetInt64(int64(priv.E))
de.Mul(de, priv.D)
for _, prime := range priv.Primes {
pminus1 := new(big.Int).Sub(prime, bigOne)
congruence.Mod(de, pminus1)
if congruence.Cmp(bigOne) != 0 {
return errors.New("crypto/rsa: invalid exponents")
}
}
return nil
}
示例8: encodeBase58Check
func encodeBase58Check(val []byte) []byte {
const alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
// payload
p := make([]byte, 1+len(val)) // version byte (0x00) + val
copy(p[1:], val)
h1 := sha256.Sum256(p)
h2 := sha256.Sum256(h1[:])
// value as []byte
v := make([]byte, len(p)+4) // payload + first 4 bytes of h2
copy(v, p)
copy(v[len(p):], h2[:4])
var res []byte
x := new(big.Int).SetBytes(v)
y := big.NewInt(58)
m, zero := new(big.Int), new(big.Int)
// convert to base58
for x.Cmp(zero) > 0 {
x, m = x.DivMod(x, y, m)
res = append(res, alphabet[m.Int64()])
}
// append '1' for each leading zero byte in value
for i := 0; v[i] == 0; i++ {
res = append(res, alphabet[0])
}
// reverse
for i, j := 0, len(res)-1; i < j; i, j = i+1, j-1 {
res[i], res[j] = res[j], res[i]
}
return res
}
示例9: Broadcast
// Returns the list of nodes that a broadcast message should be sent to. An
// optional ex node can be specified to exclude it from the list.
func (t *Topic) Broadcast(ex *big.Int) []*big.Int {
t.lock.RLock()
defer t.lock.RUnlock()
// Gather all the nodes to broadcast to
nodes := make([]*big.Int, len(t.nodes), len(t.nodes)+1)
copy(nodes, t.nodes)
if t.parent != nil {
nodes = append(nodes, t.parent)
}
// If exclusion is needed, do it
if ex != nil {
// Sort the nodes and do a binary search on them
sortext.BigInts(nodes)
idx := sortext.SearchBigInts(nodes, ex)
// Swap out with the last if found
if idx < len(nodes) && ex.Cmp(nodes[idx]) == 0 {
last := len(nodes) - 1
nodes[idx] = nodes[last]
nodes = nodes[:last]
}
}
return nodes
}
示例10: Disassemble
// Disassemble disassembles the byte code and returns the string
// representation (human readable opcodes).
func Disassemble(script []byte) (asm []string) {
pc := new(big.Int)
for {
if pc.Cmp(big.NewInt(int64(len(script)))) >= 0 {
return
}
// Get the memory location of pc
val := script[pc.Int64()]
// Get the opcode (it must be an opcode!)
op := OpCode(val)
asm = append(asm, fmt.Sprintf("%v", op))
switch op {
case PUSH1, PUSH2, PUSH3, PUSH4, PUSH5, PUSH6, PUSH7, PUSH8, PUSH9, PUSH10, PUSH11, PUSH12, PUSH13, PUSH14, PUSH15, PUSH16, PUSH17, PUSH18, PUSH19, PUSH20, PUSH21, PUSH22, PUSH23, PUSH24, PUSH25, PUSH26, PUSH27, PUSH28, PUSH29, PUSH30, PUSH31, PUSH32:
pc.Add(pc, common.Big1)
a := int64(op) - int64(PUSH1) + 1
if int(pc.Int64()+a) > len(script) {
return nil
}
data := script[pc.Int64() : pc.Int64()+a]
if len(data) == 0 {
data = []byte{0}
}
asm = append(asm, fmt.Sprintf("0x%x", data))
pc.Add(pc, big.NewInt(a-1))
}
pc.Add(pc, common.Big1)
}
}
示例11: 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
}
示例12: calcMemSize
func calcMemSize(off, l *big.Int) *big.Int {
if l.Cmp(common.Big0) == 0 {
return common.Big0
}
return new(big.Int).Add(off, l)
}
示例13: 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 *TwistedEdwardsCurve, sigss [][]byte) (*big.Int,
error) {
combinedSigS := new(big.Int).SetInt64(0)
for i, sigs := range sigss {
sigsBI := EncodedBytesToBigInt(copyBytes(sigs))
if sigsBI.Cmp(zero) == 0 {
str := fmt.Sprintf("sig s %v is zero", i)
return nil, fmt.Errorf("%v", str)
}
if sigsBI.Cmp(curve.N) >= 0 {
str := fmt.Sprintf("sig s %v is out of bounds", i)
return nil, fmt.Errorf("%v", str)
}
combinedSigS = ScalarAdd(combinedSigS, sigsBI)
combinedSigS.Mod(combinedSigS, curve.N)
}
if combinedSigS.Cmp(zero) == 0 {
str := fmt.Sprintf("combined sig s %v is zero", combinedSigS)
return nil, fmt.Errorf("%v", str)
}
return combinedSigS, nil
}
示例14: VerifyKeyPair
// Verify the secret key's range and if a test message signed with it verifies OK
// Returns nil if everything looks OK
func VerifyKeyPair(priv []byte, publ []byte) error {
var sig Signature
const TestMessage = "Just some test message..."
hash := Sha2Sum([]byte(TestMessage))
D := new(big.Int).SetBytes(priv)
if D.Cmp(big.NewInt(0)) == 0 {
return errors.New("pubkey value is zero")
}
if D.Cmp(&secp256k1.TheCurve.Order.Int) != -1 {
return errors.New("pubkey value is too big")
}
r, s, e := EcdsaSign(priv, hash[:])
if e != nil {
return errors.New("EcdsaSign failed: " + e.Error())
}
sig.R.Set(r)
sig.S.Set(s)
ok := EcdsaVerify(publ, sig.Bytes(), hash[:])
if !ok {
return errors.New("EcdsaVerify failed")
}
return nil
}
示例15: NewMaster
// NewMaster creates a new master node for use in creating a hierarchical
// deterministic key chain. The seed must be between 128 and 512 bits and
// should be generated by a cryptographically secure random generation source.
//
// NOTE: There is an extremely small chance (< 1 in 2^127) the provided seed
// will derive to an unusable secret key. The ErrUnusable error will be
// returned if this should occur, so the caller must check for it and generate a
// new seed accordingly.
func NewMaster(seed []byte, net *chaincfg.Params) (*ExtendedKey, error) {
// Per [BIP32], the seed must be in range [MinSeedBytes, MaxSeedBytes].
if len(seed) < MinSeedBytes || len(seed) > MaxSeedBytes {
return nil, ErrInvalidSeedLen
}
// First take the HMAC-SHA512 of the master key and the seed data:
// I = HMAC-SHA512(Key = "Bitcoin seed", Data = S)
hmac512 := hmac.New(sha512.New, masterKey)
hmac512.Write(seed)
lr := hmac512.Sum(nil)
// Split "I" into two 32-byte sequences Il and Ir where:
// Il = master secret key
// Ir = master chain code
secretKey := lr[:len(lr)/2]
chainCode := lr[len(lr)/2:]
// Ensure the key in usable.
secretKeyNum := new(big.Int).SetBytes(secretKey)
if secretKeyNum.Cmp(btcec.S256().N) >= 0 || secretKeyNum.Sign() == 0 {
return nil, ErrUnusableSeed
}
parentFP := []byte{0x00, 0x00, 0x00, 0x00}
return newExtendedKey(net.HDPrivateKeyID[:], secretKey, chainCode,
parentFP, 0, 0, true), nil
}