github.com/halybang/go-ethereum@v1.0.5-0.20180325041310-3b262bc1367c/crypto/crypto.go (about)

     1  // Copyright 2018 Wanchain Foundation Ltd
     2  // Copyright 2014 The go-ethereum Authors
     3  // This file is part of the go-ethereum library.
     4  //
     5  // The go-ethereum library is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU Lesser General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // The go-ethereum library is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  // GNU Lesser General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU Lesser General Public License
    16  // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
    17  
    18  package crypto
    19  
    20  import (
    21  	"crypto/ecdsa"
    22  	"crypto/elliptic"
    23  	"crypto/rand"
    24  	"encoding/hex"
    25  	"errors"
    26  	"fmt"
    27  	"io"
    28  	"io/ioutil"
    29  	"math/big"
    30  	"os"
    31  
    32  	"github.com/wanchain/go-wanchain/common"
    33  	"github.com/wanchain/go-wanchain/common/hexutil"
    34  	"github.com/wanchain/go-wanchain/common/math"
    35  	"github.com/wanchain/go-wanchain/crypto/sha3"
    36  	"github.com/wanchain/go-wanchain/rlp"
    37  
    38  	"crypto/aes"
    39  	"crypto/cipher"
    40  	"crypto/rsa"
    41  
    42  	Mrand "math/rand"
    43  
    44  	"github.com/wanchain/go-wanchain/log"
    45  )
    46  
    47  var (
    48  	secp256k1_N, _  = new(big.Int).SetString("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", 16)
    49  	secp256k1_halfN = new(big.Int).Div(secp256k1_N, big.NewInt(2))
    50  )
    51  
    52  // Keccak256 calculates and returns the Keccak256 hash of the input data.
    53  func Keccak256(data ...[]byte) []byte {
    54  	d := sha3.NewKeccak256()
    55  	for _, b := range data {
    56  		d.Write(b)
    57  	}
    58  	return d.Sum(nil)
    59  }
    60  
    61  // Keccak256Hash calculates and returns the Keccak256 hash of the input data,
    62  // converting it to an internal Hash data structure.
    63  func Keccak256Hash(data ...[]byte) (h common.Hash) {
    64  	d := sha3.NewKeccak256()
    65  	for _, b := range data {
    66  		d.Write(b)
    67  	}
    68  	d.Sum(h[:0])
    69  	return h
    70  }
    71  
    72  // Keccak512 calculates and returns the Keccak512 hash of the input data.
    73  func Keccak512(data ...[]byte) []byte {
    74  	d := sha3.NewKeccak512()
    75  	for _, b := range data {
    76  		d.Write(b)
    77  	}
    78  	return d.Sum(nil)
    79  }
    80  
    81  // Creates an ethereum address given the bytes and the nonce
    82  func CreateAddress(b common.Address, nonce uint64) common.Address {
    83  	data, _ := rlp.EncodeToBytes([]interface{}{b, nonce})
    84  	return common.BytesToAddress(Keccak256(data)[12:])
    85  }
    86  
    87  // ToECDSA creates a private key with the given D value.
    88  func ToECDSA(d []byte) (*ecdsa.PrivateKey, error) {
    89  	return toECDSA(d, true)
    90  }
    91  
    92  // ToECDSAUnsafe blidly converts a binary blob to a private key. It should almost
    93  // never be used unless you are sure the input is valid and want to avoid hitting
    94  // errors due to bad origin encoding (0 prefixes cut off).
    95  func ToECDSAUnsafe(d []byte) *ecdsa.PrivateKey {
    96  	if len(d) == 0 {
    97  		return nil
    98  	}
    99  	priv, _ := toECDSA(d, false)
   100  	return priv
   101  }
   102  
   103  // toECDSA creates a private key with the given D value. The strict parameter
   104  // controls whether the key's length should be enforced at the curve size or
   105  // it can also accept legacy encodings (0 prefixes).
   106  func toECDSA(d []byte, strict bool) (*ecdsa.PrivateKey, error) {
   107  	priv := new(ecdsa.PrivateKey)
   108  	priv.PublicKey.Curve = S256()
   109  	if strict && 8*len(d) != priv.Params().BitSize {
   110  		return nil, fmt.Errorf("invalid length, need %d bits", priv.Params().BitSize)
   111  	}
   112  	priv.D = new(big.Int).SetBytes(d)
   113  	priv.PublicKey.X, priv.PublicKey.Y = priv.PublicKey.Curve.ScalarBaseMult(d)
   114  	return priv, nil
   115  }
   116  
   117  // FromECDSA exports a private key into a binary dump.
   118  func FromECDSA(priv *ecdsa.PrivateKey) []byte {
   119  	if priv == nil {
   120  		return nil
   121  	}
   122  	return math.PaddedBigBytes(priv.D, priv.Params().BitSize/8)
   123  }
   124  
   125  func ToECDSAPub(pub []byte) *ecdsa.PublicKey {
   126  	//check input error
   127  	if len(pub) != 65{
   128  		return nil
   129  	}
   130  
   131  	x, y := elliptic.Unmarshal(S256(), pub)
   132  	if x == nil || y == nil {
   133  		return nil
   134  	}
   135  
   136  	return &ecdsa.PublicKey{Curve: S256(), X: x, Y: y}
   137  }
   138  
   139  func FromECDSAPub(pub *ecdsa.PublicKey) []byte {
   140  	if pub == nil || pub.X == nil || pub.Y == nil {
   141  		return nil
   142  	}
   143  	return elliptic.Marshal(S256(), pub.X, pub.Y)
   144  }
   145  
   146  // HexToECDSA parses a secp256k1 private key.
   147  func HexToECDSA(hexkey string) (*ecdsa.PrivateKey, error) {
   148  	b, err := hex.DecodeString(hexkey)
   149  	if err != nil {
   150  		return nil, errors.New("invalid hex string")
   151  	}
   152  	return ToECDSA(b)
   153  }
   154  
   155  // LoadECDSA loads a secp256k1 private key from the given file.
   156  func LoadECDSA(file string) (*ecdsa.PrivateKey, error) {
   157  	buf := make([]byte, 64)
   158  	fd, err := os.Open(file)
   159  	if err != nil {
   160  		return nil, err
   161  	}
   162  	defer fd.Close()
   163  	if _, err := io.ReadFull(fd, buf); err != nil {
   164  		return nil, err
   165  	}
   166  
   167  	key, err := hex.DecodeString(string(buf))
   168  	if err != nil {
   169  		return nil, err
   170  	}
   171  	return ToECDSA(key)
   172  }
   173  
   174  // SaveECDSA saves a secp256k1 private key to the given file with
   175  // restrictive permissions. The key data is saved hex-encoded.
   176  func SaveECDSA(file string, key *ecdsa.PrivateKey) error {
   177  	k := hex.EncodeToString(FromECDSA(key))
   178  	return ioutil.WriteFile(file, []byte(k), 0600)
   179  }
   180  
   181  func GenerateKey() (*ecdsa.PrivateKey, error) {
   182  	return ecdsa.GenerateKey(S256(), rand.Reader)
   183  }
   184  
   185  // ValidateSignatureValues verifies whether the signature values are valid with
   186  // the given chain rules. The v value is assumed to be either 0 or 1.
   187  func ValidateSignatureValues(v byte, r, s *big.Int, homestead bool) bool {
   188  	if r.Cmp(common.Big1) < 0 || s.Cmp(common.Big1) < 0 {
   189  		return false
   190  	}
   191  	// reject upper range of s values (ECDSA malleability)
   192  	// see discussion in secp256k1/libsecp256k1/include/secp256k1.h
   193  	if homestead && s.Cmp(secp256k1_halfN) > 0 {
   194  		return false
   195  	}
   196  	// Frontier: allow s to be in full N range
   197  	return r.Cmp(secp256k1_N) < 0 && s.Cmp(secp256k1_N) < 0 && (v == 0 || v == 1)
   198  }
   199  
   200  func PubkeyToAddress(p ecdsa.PublicKey) common.Address {
   201  	pubBytes := FromECDSAPub(&p)
   202  	return common.BytesToAddress(Keccak256(pubBytes[1:])[12:])
   203  }
   204  
   205  func zeroBytes(bytes []byte) {
   206  	for i := range bytes {
   207  		bytes[i] = 0
   208  	}
   209  }
   210  
   211  
   212  // PublicKeyToInt converts PublicKey data structure to Big int data structure
   213  // and return outInt[0] as return value. 
   214  // storage structure is like ((x,y)(x,y)(x,y)(x,y)....)
   215  func PublicKeyToInt(PublicKeys ...*ecdsa.PublicKey) []*hexutil.Big {
   216  	n := len(PublicKeys)
   217  	outInt := make([]*hexutil.Big, 2*n)
   218  	for i := 0; i < n; i++ {
   219  		outInt[2*i] = (*hexutil.Big)(PublicKeys[i].X)
   220  		outInt[2*i+1] = (*hexutil.Big)(PublicKeys[i].Y)
   221  	}
   222  
   223  	return outInt
   224  }
   225  
   226  // IntToPublicKey converts Big int data structure to PublicKey data structure
   227  func IntToPublicKey(in ...*big.Int) []*ecdsa.PublicKey {
   228  	n := len(in)
   229  	PublicKeys := make([]*ecdsa.PublicKey, n/2)
   230  	for i := 0; i < n/2; i++ {
   231  		//PublicKeys[i] = ToECDSAPub(in[i].Bytes())
   232  		PublicKeys[i] = new(ecdsa.PublicKey)
   233  		PublicKeys[i].X = in[2*i]
   234  		PublicKeys[i].Y = in[2*i+1]
   235  		PublicKeys[i].Curve = S256()
   236  	}
   237  	return PublicKeys
   238  }
   239  
   240  // AES encryption algorithm
   241  // Shi,TeemoGuo added
   242  func aesCTRXOR(key, inText, iv []byte) ([]byte, error) {
   243  	// AES-128 is selected due to size of encryptKey.
   244  	aesBlock, err := aes.NewCipher(key)
   245  	if err != nil {
   246  		return nil, err
   247  	}
   248  	stream := cipher.NewCTR(aesBlock, iv)
   249  	outText := make([]byte, len(inText))
   250  	stream.XORKeyStream(outText, inText)
   251  	return outText, err
   252  }
   253  
   254  // AES encryption algorithm interface
   255  // Shi,TeemoGuo added
   256  func AesCTRXOR(key, inText, iv []byte) ([]byte, error) {
   257  	return aesCTRXOR(key, inText, iv)
   258  }
   259  
   260  
   261  var bigOne = big.NewInt(1)
   262  var bigZero = big.NewInt(0)
   263  var one = new(big.Int).SetInt64(1)
   264  
   265  func modInverse(a, n *big.Int) (ia *big.Int, ok bool) {
   266  	g := new(big.Int)
   267  	x := new(big.Int)
   268  	y := new(big.Int)
   269  	g.GCD(x, y, a, n)
   270  	if g.Cmp(bigOne) != 0 {
   271  		// In this case, a and n aren't coprime and we cannot calculate
   272  		// the inverse. This happens because the values of n are nearly
   273  		// prime (being the product of two primes) rather than truly
   274  		// prime.
   275  		return
   276  	}
   277  
   278  	if x.Cmp(bigOne) < 0 {
   279  		// 0 is not the multiplicative inverse of any element so, if x
   280  		// < 1, then x is negative.
   281  		x.Add(x, n)
   282  	}
   283  
   284  	return x, true
   285  }
   286  
   287  // RSA encryption algorithm interface
   288  // Shi,TeemoGuo added
   289  func Rsa_encrypt(c *big.Int, pub *rsa.PublicKey, m *big.Int) *big.Int {
   290  	e := big.NewInt(int64(pub.E))
   291  	c.Exp(m, e, pub.N)
   292  	return c
   293  }
   294  
   295  // RSA decryption algorithm interface
   296  // Shi,TeemoGuo added
   297  func Rsa_decrypt(random io.Reader, priv *rsa.PrivateKey, c *big.Int) (m *big.Int, err error) {
   298  	// TODO(agl): can we get away with reusing blinds?
   299  	if c.Cmp(priv.N) > 0 {
   300  		err = rsa.ErrDecryption
   301  		return
   302  	}
   303  	if priv.N.Sign() == 0 {
   304  		return nil, rsa.ErrDecryption
   305  	}
   306  
   307  	var ir *big.Int
   308  	if random != nil {
   309  		// Blinding enabled. Blinding involves multiplying c by r^e.
   310  		// Then the decryption operation performs (m^e * r^e)^d mod n
   311  		// which equals mr mod n. The factor of r can then be removed
   312  		// by multiplying by the multiplicative inverse of r.
   313  
   314  		var r *big.Int
   315  
   316  		for {
   317  			r, err = rand.Int(random, priv.N)
   318  			if err != nil {
   319  				return
   320  			}
   321  			if r.Cmp(bigZero) == 0 {
   322  				r = bigOne
   323  			}
   324  			var ok bool
   325  			ir, ok = modInverse(r, priv.N)
   326  			if ok {
   327  				break
   328  			}
   329  		}
   330  		bigE := big.NewInt(int64(priv.E))
   331  		rpowe := new(big.Int).Exp(r, bigE, priv.N) // N != 0
   332  		cCopy := new(big.Int).Set(c)
   333  		cCopy.Mul(cCopy, rpowe)
   334  		cCopy.Mod(cCopy, priv.N)
   335  		c = cCopy
   336  	}
   337  
   338  	if priv.Precomputed.Dp == nil {
   339  		m = new(big.Int).Exp(c, priv.D, priv.N)
   340  	} else {
   341  		// We have the precalculated values needed for the CRT.
   342  		m = new(big.Int).Exp(c, priv.Precomputed.Dp, priv.Primes[0])
   343  		m2 := new(big.Int).Exp(c, priv.Precomputed.Dq, priv.Primes[1])
   344  		m.Sub(m, m2)
   345  		if m.Sign() < 0 {
   346  			m.Add(m, priv.Primes[0])
   347  		}
   348  		m.Mul(m, priv.Precomputed.Qinv)
   349  		m.Mod(m, priv.Primes[0])
   350  		m.Mul(m, priv.Primes[1])
   351  		m.Add(m, m2)
   352  
   353  		for i, values := range priv.Precomputed.CRTValues {
   354  			prime := priv.Primes[2+i]
   355  			m2.Exp(c, values.Exp, prime)
   356  			m2.Sub(m2, m)
   357  			m2.Mul(m2, values.Coeff)
   358  			m2.Mod(m2, prime)
   359  			if m2.Sign() < 0 {
   360  				m2.Add(m2, prime)
   361  			}
   362  			m2.Mul(m2, values.R)
   363  			m.Add(m, m2)
   364  		}
   365  	}
   366  
   367  	if ir != nil {
   368  		// Unblind.
   369  		m.Mul(m, ir)
   370  		m.Mod(m, priv.N)
   371  	}
   372  
   373  	return
   374  }
   375  
   376  // randFieldElement2528 returns a random element of the field
   377  func randFieldElement2528(rand io.Reader) (k *big.Int, err error) {
   378  	params := S256().Params()
   379  	b := make([]byte, params.BitSize/8+8)
   380  	_, err = io.ReadFull(rand, b)
   381  	if err != nil {
   382  		return
   383  	}
   384  	k = new(big.Int).SetBytes(b)
   385  	n := new(big.Int).Sub(params.N, one)
   386  	k.Mod(k, n)
   387  	k.Add(k, one)
   388  
   389  	return
   390  }
   391  
   392  // calc [x]Hash(P)
   393  func xScalarHashP(x []byte, pub *ecdsa.PublicKey) (I *ecdsa.PublicKey) {
   394  	KeyImg := new(ecdsa.PublicKey)
   395  	I = new(ecdsa.PublicKey)
   396  	KeyImg.X, KeyImg.Y = S256().ScalarMult(pub.X, pub.Y, Keccak256(FromECDSAPub(pub))) //Hash(P)
   397  	I.X, I.Y = S256().ScalarMult(KeyImg.X, KeyImg.Y, x)
   398  	I.Curve = S256()
   399  	return
   400  }
   401  
   402  var (
   403  	ErrInvalidRingSignParams = errors.New("invalid ring sign params")
   404  	ErrRingSignFail          = errors.New("ring sign fail")
   405  )
   406  
   407  // RingSign is the function of ring signature
   408  // Pengbo added, Shi,TeemoGuo revised
   409  func RingSign(M []byte, x *big.Int, PublicKeys []*ecdsa.PublicKey) ([]*ecdsa.PublicKey, *ecdsa.PublicKey, []*big.Int, []*big.Int, error) {
   410  	if M == nil || x == nil || len(PublicKeys) == 0 {
   411  		return nil, nil, nil, nil, ErrInvalidRingSignParams
   412  	}
   413  
   414  	for _, publicKey := range PublicKeys {
   415  		if publicKey == nil || publicKey.X == nil || publicKey.Y == nil {
   416  			return nil, nil, nil, nil, ErrInvalidRingSignParams
   417  		}
   418  	}
   419  
   420  	n := len(PublicKeys)
   421  	I := xScalarHashP(x.Bytes(), PublicKeys[0]) //Key Image
   422  	if I == nil || I.X == nil || I.Y == nil {
   423  		return nil, nil, nil, nil, ErrRingSignFail
   424  	}
   425  
   426  	s := Mrand.Intn(n) //s is the random position for real key 
   427  	if s > 0 {
   428  		PublicKeys[0], PublicKeys[s] = PublicKeys[s], PublicKeys[0] //exchange position
   429  	}
   430  
   431  	var (
   432  		q = make([]*big.Int, n)
   433  		w = make([]*big.Int, n)
   434  	)
   435  
   436  	SumC := new(big.Int).SetInt64(0)
   437  	Lpub := new(ecdsa.PublicKey)
   438  	d := sha3.NewKeccak256()
   439  	d.Write(M)
   440  
   441  	var err error
   442  	for i := 0; i < n; i++ {
   443  		q[i], err = randFieldElement2528(rand.Reader)
   444  		if err != nil {
   445  			return nil, nil, nil, nil, err
   446  		}
   447  
   448  		w[i], err = randFieldElement2528(rand.Reader)
   449  		if err != nil {
   450  			return nil, nil, nil, nil, err
   451  		}
   452  
   453  		Lpub.X, Lpub.Y = S256().ScalarBaseMult(q[i].Bytes()) //[qi]G
   454  		if Lpub.X == nil || Lpub.Y == nil {
   455  			return nil, nil, nil, nil, ErrRingSignFail
   456  		}
   457  
   458  		if i != s {
   459  			Ppub := new(ecdsa.PublicKey)
   460  			Ppub.X, Ppub.Y = S256().ScalarMult(PublicKeys[i].X, PublicKeys[i].Y, w[i].Bytes()) //[wi]Pi
   461  			if Ppub.X == nil || Ppub.Y == nil {
   462  				return nil, nil, nil, nil, ErrRingSignFail
   463  			}
   464  
   465  			Lpub.X, Lpub.Y = S256().Add(Lpub.X, Lpub.Y, Ppub.X, Ppub.Y) //[qi]G+[wi]Pi
   466  
   467  			SumC.Add(SumC, w[i])
   468  			SumC.Mod(SumC, secp256k1_N)
   469  		}
   470  
   471  		d.Write(FromECDSAPub(Lpub))
   472  	}
   473  
   474  	Rpub := new(ecdsa.PublicKey)
   475  	for i := 0; i < n; i++ {
   476  		Rpub = xScalarHashP(q[i].Bytes(), PublicKeys[i]) //[qi]HashPi
   477  		if Rpub == nil || Rpub.X == nil || Rpub.Y == nil {
   478  			return nil, nil, nil, nil, ErrRingSignFail
   479  		}
   480  
   481  		if i != s {
   482  			Ppub := new(ecdsa.PublicKey)
   483  			Ppub.X, Ppub.Y = S256().ScalarMult(I.X, I.Y, w[i].Bytes()) //[wi]I
   484  			if Ppub.X == nil || Ppub.Y == nil {
   485  				return nil, nil, nil, nil, ErrRingSignFail
   486  			}
   487  
   488  			Rpub.X, Rpub.Y = S256().Add(Rpub.X, Rpub.Y, Ppub.X, Ppub.Y) //[qi]HashPi+[wi]I
   489  		}
   490  
   491  		d.Write(FromECDSAPub(Rpub))
   492  	}
   493  
   494  	Cs := new(big.Int).SetBytes(d.Sum(nil)) //hash(m,Li,Ri)
   495  	Cs.Sub(Cs, SumC)
   496  	Cs.Mod(Cs, secp256k1_N)
   497  
   498  	tmp := new(big.Int).Mul(Cs, x)
   499  	Rs := new(big.Int).Sub(q[s], tmp)
   500  	Rs.Mod(Rs, secp256k1_N)
   501  	w[s] = Cs
   502  	q[s] = Rs
   503  
   504  	return PublicKeys, I, w, q, nil
   505  }
   506  
   507  // VerifyRingSign verifies the validity of ring signature
   508  // Pengbo added, Shi,TeemoGuo revised
   509  func VerifyRingSign(M []byte, PublicKeys []*ecdsa.PublicKey, I *ecdsa.PublicKey, c []*big.Int, r []*big.Int) bool {
   510  	if M == nil || PublicKeys == nil || I == nil || c == nil || r == nil {
   511  		return false
   512  	}
   513  
   514  	if len(PublicKeys) == 0 || len(PublicKeys) != len(c) || len(PublicKeys) != len(r) {
   515  		return false
   516  	}
   517  
   518  	n := len(PublicKeys)
   519  	for i := 0; i < n; i++ {
   520  		if PublicKeys[i] == nil || PublicKeys[i].X == nil || PublicKeys[i].Y == nil ||
   521  			c[i] == nil || r[i] == nil {
   522  			return false
   523  		}
   524  	}
   525  
   526  	log.Debug("M info", "R", 0, "M", common.ToHex(M))
   527  	for i := 0; i < n; i++ {
   528  		log.Debug("publicKeys", "i", i, "publickey", common.ToHex(FromECDSAPub(PublicKeys[i])))
   529  	}
   530  
   531  	log.Debug("image info", "I", common.ToHex(FromECDSAPub(I)))
   532  	for i := 0; i < n; i++ {
   533  		log.Debug("c info", "i", i, "c", common.ToHex(c[i].Bytes()))
   534  	}
   535  
   536  	for i := 0; i < n; i++ {
   537  		log.Debug("r info", "i", i, "r", common.ToHex(r[i].Bytes()))
   538  	}
   539  
   540  	SumC := new(big.Int).SetInt64(0)
   541  	Lpub := new(ecdsa.PublicKey)
   542  	d := sha3.NewKeccak256()
   543  	d.Write(M)
   544  
   545  	//hash(M,Li,Ri)
   546  	for i := 0; i < n; i++ {
   547  		Lpub.X, Lpub.Y = S256().ScalarBaseMult(r[i].Bytes()) //[ri]G
   548  		if Lpub.X == nil || Lpub.Y == nil {
   549  			return false
   550  		}
   551  
   552  		Ppub := new(ecdsa.PublicKey)
   553  		Ppub.X, Ppub.Y = S256().ScalarMult(PublicKeys[i].X, PublicKeys[i].Y, c[i].Bytes()) //[ci]Pi
   554  		if Ppub.X == nil || Ppub.Y == nil {
   555  			return false
   556  		}
   557  
   558  		Lpub.X, Lpub.Y = S256().Add(Lpub.X, Lpub.Y, Ppub.X, Ppub.Y) //[ri]G+[ci]Pi
   559  		SumC.Add(SumC, c[i])
   560  		SumC.Mod(SumC, secp256k1_N)
   561  		d.Write(FromECDSAPub(Lpub))
   562  		log.Debug("LPublicKeys", "i", i, "Lpub", common.ToHex(FromECDSAPub(Lpub)))
   563  	}
   564  
   565  	Rpub := new(ecdsa.PublicKey)
   566  	for i := 0; i < n; i++ {
   567  		Rpub = xScalarHashP(r[i].Bytes(), PublicKeys[i]) //[qi]HashPi
   568  		if Rpub == nil || Rpub.X == nil || Rpub.Y == nil {
   569  			return false
   570  		}
   571  
   572  		Ppub := new(ecdsa.PublicKey)
   573  		Ppub.X, Ppub.Y = S256().ScalarMult(I.X, I.Y, c[i].Bytes()) //[wi]I
   574  		if Ppub.X == nil || Ppub.Y == nil {
   575  			return false
   576  		}
   577  
   578  		Rpub.X, Rpub.Y = S256().Add(Rpub.X, Rpub.Y, Ppub.X, Ppub.Y) //[qi]HashPi+[wi]I
   579  		log.Debug("RPublicKeys", "i", i, "Rpub", common.ToHex(FromECDSAPub(Rpub)))
   580  
   581  		d.Write(FromECDSAPub(Rpub))
   582  	}
   583  
   584  	hash := new(big.Int).SetBytes(d.Sum(nil)) //hash(m,Li,Ri)
   585  	log.Debug("hash info", "i", 0, "hash", common.ToHex(hash.Bytes()))
   586  
   587  	hash.Mod(hash, secp256k1_N)
   588  	log.Debug("hash info", "i", 2, "hash", common.ToHex(hash.Bytes()))
   589  	log.Debug("SumC info", "i", 3, "SumC", common.ToHex(SumC.Bytes()))
   590  
   591  	return hash.Cmp(SumC) == 0
   592  }
   593  
   594  // A1=[hash([r]B)]G+A
   595  // Pengbo added, TeemoGuo revised 
   596  func generateA1(r []byte, A *ecdsa.PublicKey, B *ecdsa.PublicKey) ecdsa.PublicKey {
   597  	A1 := new(ecdsa.PublicKey)
   598  	A1.X, A1.Y = S256().ScalarMult(B.X, B.Y, r)   //A1=[r]B
   599  	A1Bytes := Keccak256(FromECDSAPub(A1))        //hash([r]B)
   600  	A1.X, A1.Y = S256().ScalarBaseMult(A1Bytes)   //[hash([r]B)]G
   601  	A1.X, A1.Y = S256().Add(A1.X, A1.Y, A.X, A.Y) //A1=[hash([r]B)]G+A
   602  	A1.Curve = S256()
   603  	return *A1
   604  }
   605  
   606  func CompareA1(b []byte, A *ecdsa.PublicKey, S1 *ecdsa.PublicKey, A1 *ecdsa.PublicKey) bool {
   607  	A1n := generateA1(b, A, S1)
   608  	if A1.X.Cmp(A1n.X) == 0 && A1.Y.Cmp(A1n.Y) == 0 {
   609  		return true
   610  	}
   611  	return false
   612  }
   613  
   614  // generateOneTimeKey2528 generates an OTA account for receiver using receiver's publickey
   615  // Pengbo added, TeemoGuo revised
   616  func generateOneTimeKey2528(A *ecdsa.PublicKey, B *ecdsa.PublicKey) (A1 *ecdsa.PublicKey, R *ecdsa.PublicKey, err error) {
   617  	RPrivateKey, err := GenerateKey()
   618  	if err != nil {
   619  		return nil, nil, err
   620  	}
   621  	R = &RPrivateKey.PublicKey
   622  	A1 = new(ecdsa.PublicKey)
   623  	*A1 = generateA1(RPrivateKey.D.Bytes(), A, B)
   624  	return A1, R, err
   625  }
   626  
   627  // Generate OTA account interface
   628  func GenerateOneTimeKey(AX string, AY string, BX string, BY string) (ret []string, err error) {
   629  	bytesAX, err := hexutil.Decode(AX)
   630  	if err != nil {
   631  		return
   632  	}
   633  	bytesAY, err := hexutil.Decode(AY)
   634  	if err != nil {
   635  		return
   636  	}
   637  	bytesBX, err := hexutil.Decode(BX)
   638  	if err != nil {
   639  		return
   640  	}
   641  	bytesBY, err := hexutil.Decode(BY)
   642  	if err != nil {
   643  		return
   644  	}
   645  	bnAX := new(big.Int).SetBytes(bytesAX)
   646  	bnAY := new(big.Int).SetBytes(bytesAY)
   647  	bnBX := new(big.Int).SetBytes(bytesBX)
   648  	bnBY := new(big.Int).SetBytes(bytesBY)
   649  
   650  	pa := &ecdsa.PublicKey{X: bnAX, Y: bnAY}
   651  	pb := &ecdsa.PublicKey{X: bnBX, Y: bnBY}
   652  
   653  	generatedA1, generatedR, err := generateOneTimeKey2528(pa, pb)
   654  	return hexutil.PKPair2HexSlice(generatedA1, generatedR), nil
   655  }
   656  
   657  // GenerteOTAPrivateKey generates the privatekey for an OTA account using receiver's main account's privatekey
   658  // Pengbo added, TeemoGuo revised
   659  func GenerteOTAPrivateKey(privateKey *ecdsa.PrivateKey, privateKey2 *ecdsa.PrivateKey, AX string, AY string, BX string, BY string) (retPub *ecdsa.PublicKey, retPriv1 *ecdsa.PrivateKey, retPriv2 *ecdsa.PrivateKey, err error) {
   660  	bytesAX, err := hexutil.Decode(AX)
   661  	if err != nil {
   662  		return
   663  	}
   664  	bytesAY, err := hexutil.Decode(AY)
   665  	if err != nil {
   666  		return
   667  	}
   668  	bytesBX, err := hexutil.Decode(BX)
   669  	if err != nil {
   670  		return
   671  	}
   672  	bytesBY, err := hexutil.Decode(BY)
   673  	if err != nil {
   674  		return
   675  	}
   676  	bnAX := new(big.Int).SetBytes(bytesAX)
   677  	bnAY := new(big.Int).SetBytes(bytesAY)
   678  	bnBX := new(big.Int).SetBytes(bytesBX)
   679  	bnBY := new(big.Int).SetBytes(bytesBY)
   680  
   681  	retPub = &ecdsa.PublicKey{X: bnAX, Y: bnAY}
   682  	pb := &ecdsa.PublicKey{X: bnBX, Y: bnBY}
   683  	retPriv1, retPriv2, err = GenerateOneTimePrivateKey2528(privateKey, privateKey2, retPub, pb)
   684  	return
   685  }
   686  
   687  func GenerateOneTimePrivateKey2528(privateKey *ecdsa.PrivateKey, privateKey2 *ecdsa.PrivateKey, destPubA *ecdsa.PublicKey, destPubB *ecdsa.PublicKey) (retPriv1 *ecdsa.PrivateKey, retPriv2 *ecdsa.PrivateKey, err error) {
   688  	pub := new(ecdsa.PublicKey)
   689  	pub.X, pub.Y = S256().ScalarMult(destPubB.X, destPubB.Y, privateKey2.D.Bytes()) //[b]R
   690  	k := new(big.Int).SetBytes(Keccak256(FromECDSAPub(pub)))                        //hash([b]R)
   691  	k.Add(k, privateKey.D)                                                          //hash([b]R)+a
   692  	k.Mod(k, S256().Params().N)                                                     //mod to feild N
   693  
   694  	retPriv1 = new(ecdsa.PrivateKey)
   695  	retPriv2 = new(ecdsa.PrivateKey)
   696  
   697  	retPriv1.D = k
   698  	retPriv2.D = new(big.Int).SetInt64(0)
   699  	return retPriv1, retPriv2, nil
   700  }
   701  
   702  /////////////////////////////////////////jia added////////////////////////////////////////////////////////////////
   703  const (
   704  	// alphabet is the modified base58 alphabet used by Bitcoin.
   705  	alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
   706  
   707  	alphabetIdx0 = '1'
   708  )
   709  
   710  var b58 = [256]byte{
   711  	255, 255, 255, 255, 255, 255, 255, 255,
   712  	255, 255, 255, 255, 255, 255, 255, 255,
   713  	255, 255, 255, 255, 255, 255, 255, 255,
   714  	255, 255, 255, 255, 255, 255, 255, 255,
   715  	255, 255, 255, 255, 255, 255, 255, 255,
   716  	255, 255, 255, 255, 255, 255, 255, 255,
   717  	255, 0, 1, 2, 3, 4, 5, 6,
   718  	7, 8, 255, 255, 255, 255, 255, 255,
   719  	255, 9, 10, 11, 12, 13, 14, 15,
   720  	16, 255, 17, 18, 19, 20, 21, 255,
   721  	22, 23, 24, 25, 26, 27, 28, 29,
   722  	30, 31, 32, 255, 255, 255, 255, 255,
   723  	255, 33, 34, 35, 36, 37, 38, 39,
   724  	40, 41, 42, 43, 255, 44, 45, 46,
   725  	47, 48, 49, 50, 51, 52, 53, 54,
   726  	55, 56, 57, 255, 255, 255, 255, 255,
   727  	255, 255, 255, 255, 255, 255, 255, 255,
   728  	255, 255, 255, 255, 255, 255, 255, 255,
   729  	255, 255, 255, 255, 255, 255, 255, 255,
   730  	255, 255, 255, 255, 255, 255, 255, 255,
   731  	255, 255, 255, 255, 255, 255, 255, 255,
   732  	255, 255, 255, 255, 255, 255, 255, 255,
   733  	255, 255, 255, 255, 255, 255, 255, 255,
   734  	255, 255, 255, 255, 255, 255, 255, 255,
   735  	255, 255, 255, 255, 255, 255, 255, 255,
   736  	255, 255, 255, 255, 255, 255, 255, 255,
   737  	255, 255, 255, 255, 255, 255, 255, 255,
   738  	255, 255, 255, 255, 255, 255, 255, 255,
   739  	255, 255, 255, 255, 255, 255, 255, 255,
   740  	255, 255, 255, 255, 255, 255, 255, 255,
   741  	255, 255, 255, 255, 255, 255, 255, 255,
   742  	255, 255, 255, 255, 255, 255, 255, 255,
   743  }
   744  
   745  var bigRadix = big.NewInt(58)
   746  
   747  //var bigZero = big.NewInt(0)
   748  
   749  func Hex2Bytes(str string) []byte {
   750  	h, _ := hex.DecodeString(str)
   751  
   752  	return h
   753  }
   754  
   755  var FactoidPrefix = []byte{0x6c, 0x12}
   756  var WangLuMagicBigInt = new(big.Int).SetBytes(Hex2Bytes("9da26fc2e1d6ad9fdd46138906b0104ae68a65d8"))
   757  
   758  // Decode decodes a modified base58 string to a byte slice.
   759  func Decode(b string) []byte {
   760  	answer := big.NewInt(0)
   761  	j := big.NewInt(1)
   762  
   763  	scratch := new(big.Int)
   764  	for i := len(b) - 1; i >= 0; i-- {
   765  		tmp := b58[b[i]]
   766  		if tmp == 255 {
   767  			return []byte("")
   768  		}
   769  		scratch.SetInt64(int64(tmp))
   770  		scratch.Mul(j, scratch)
   771  		answer.Add(answer, scratch)
   772  		j.Mul(j, bigRadix)
   773  	}
   774  
   775  	tmpval := answer.Bytes()
   776  
   777  	var numZeros int
   778  	for numZeros = 0; numZeros < len(b); numZeros++ {
   779  		if b[numZeros] != alphabetIdx0 {
   780  			break
   781  		}
   782  	}
   783  	flen := numZeros + len(tmpval)
   784  	val := make([]byte, flen, flen)
   785  	copy(val[numZeros:], tmpval)
   786  
   787  	return val
   788  }
   789  
   790  // Encode encodes a byte slice to a modified base58 string.
   791  func Encode(b []byte) string {
   792  	x := new(big.Int)
   793  	x.SetBytes(b)
   794  
   795  	answer := make([]byte, 0, len(b)*136/100)
   796  	for x.Cmp(bigZero) > 0 {
   797  		mod := new(big.Int)
   798  		x.DivMod(x, bigRadix, mod)
   799  		answer = append(answer, alphabet[mod.Int64()])
   800  	}
   801  
   802  	// leading zero bytes
   803  	for _, i := range b {
   804  		if i != 0 {
   805  			break
   806  		}
   807  		answer = append(answer, alphabetIdx0)
   808  	}
   809  
   810  	// reverse
   811  	alen := len(answer)
   812  	for i := 0; i < alen/2; i++ {
   813  		answer[i], answer[alen-1-i] = answer[alen-1-i], answer[i]
   814  	}
   815  
   816  	return string(answer)
   817  }
   818  
   819  func getPreFixedBigInt() *big.Int {
   820  	baseBigInt := new(big.Int)
   821  	baseBigInt.SetBytes(Hex2Bytes("ffffffffffffffffffffffffffffffffffffffff"))
   822  	fmt.Println("baseBegInt: " + baseBigInt.String())
   823  	xdecimal := big.NewInt(58)
   824  	base := big.NewInt(58)
   825  	for base.Cmp(baseBigInt) <= 0 {
   826  		base = base.Mul(base, xdecimal)
   827  	}
   828  	LWangLu := big.NewInt(19)
   829  	LWangLu.Mul(LWangLu, base)
   830  	WWangLu := big.NewInt(58 * 29)
   831  	WWangLu.Mul(WWangLu, base)
   832  	retBigInt := big.NewInt(0)
   833  	retBigInt.Add(retBigInt, LWangLu)
   834  	retBigInt.Add(retBigInt, WWangLu)
   835  	fmt.Println("retBigInt: " + retBigInt.String())
   836  	fmt.Println("retBigInt hex: " + hex.EncodeToString(retBigInt.Bytes()))
   837  	return retBigInt
   838  }
   839  
   840  func otaAddress(address common.Address) string {
   841  
   842  	result := Encode(append(FactoidPrefix, Hex2Bytes(address.Hex())...))
   843  
   844  	return result
   845  }