github.com/elastos/Elastos.ELA.SideChain.ETH@v0.2.2/chainbridge-core/keystore/keyring.go (about) 1 // Copyright 2020 ChainSafe Systems 2 // SPDX-License-Identifier: LGPL-3.0-only 3 4 package keystore 5 6 import ( 7 "fmt" 8 "github.com/elastos/Elastos.ELA.SideChain.ESC/chainbridge-core/crypto" 9 "github.com/elastos/Elastos.ELA.SideChain.ESC/chainbridge-core/crypto/secp256k1" 10 "github.com/elastos/Elastos.ELA.SideChain.ESC/log" 11 ) 12 13 // The Constant "keys". These are the name that the keys are based on. This can be expanded, but 14 // any additions must be added to Keys and to insecureKeyFromAddress 15 const AliceKey = "alice" 16 const BobKey = "bob" 17 const CharlieKey = "charlie" 18 const DaveKey = "dave" 19 const EveKey = "eve" 20 21 var Keys = []string{AliceKey, BobKey, CharlieKey, DaveKey, EveKey} 22 23 // The Chain type Constants 24 const EthChain = "ethereum" 25 const SubChain = "substrate" 26 27 var TestKeyRing *TestKeyRingHolder 28 29 // TestKeyStore is a struct that holds a Keystore of all the test keys 30 type TestKeyRingHolder struct { 31 EthereumKeys map[string]*secp256k1.Keypair 32 SubstrateKeys map[string]*secp256k1.Keypair 33 } 34 35 // Init function to create a keyRing that can be accessed anywhere without having to recreate the data 36 func init() { 37 ring, err := makeEthRing() 38 if err != nil { 39 log.Error("make ring error", "error", err) 40 } 41 TestKeyRing = &TestKeyRingHolder{ 42 EthereumKeys: ring, 43 } 44 TestKeyRing.SubstrateKeys = TestKeyRing.EthereumKeys 45 } 46 47 func makeEthRing() (map[string]*secp256k1.Keypair, error) { 48 ring := map[string]*secp256k1.Keypair{} 49 for _, key := range Keys { 50 bz := padWithZeros([]byte(key), secp256k1.PrivateKeyLength) 51 kp, err := secp256k1.NewKeypairFromPrivateKey(bz) 52 if err != nil { 53 return nil, err 54 } 55 ring[key] = kp 56 } 57 58 return ring, nil 59 } 60 61 // padWithZeros adds on extra 0 bytes to make a byte array of a specified length 62 func padWithZeros(key []byte, targetLength int) []byte { 63 res := make([]byte, targetLength-len(key)) 64 return append(res, key...) 65 } 66 67 // insecureKeypairFromAddress is used for resolving addresses to test keypairs. 68 func insecureKeypairFromAddress(key string, chainType string) (crypto.Keypair, error) { 69 var kp crypto.Keypair 70 var ok bool 71 72 if chainType == EthChain { 73 kp, ok = TestKeyRing.EthereumKeys[key] 74 } else if chainType == SubChain { 75 kp, ok = TestKeyRing.SubstrateKeys[key] 76 } else { 77 return nil, fmt.Errorf("unrecognized chain type: %s", chainType) 78 } 79 80 if !ok { 81 return nil, fmt.Errorf("invalid test key selection: %s", key) 82 } 83 84 return kp, nil 85 }