aboutsummaryrefslogtreecommitdiffstats
path: root/ethchain/keypair.go
blob: 9fdc95972b71705ed98a7b94aaa8b2cd70635859 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package ethchain

import (
    "github.com/ethereum/eth-go/ethutil"
    "math/big"
)

type KeyPair struct {
    PrivateKey []byte
    PublicKey  []byte

    // The associated account
    account *Account
    state   *State
}

func NewKeyPairFromValue(val *ethutil.Value) *KeyPair {
    keyPair := &KeyPair{PrivateKey: val.Get(0).Bytes(), PublicKey: val.Get(1).Bytes()}

    return keyPair
}

func (k *KeyPair) Address() []byte {
    return ethutil.Sha3Bin(k.PublicKey[1:])[12:]
}

func (k *KeyPair) Account() *Account {
    if k.account == nil {
        k.account = k.state.GetAccount(k.Address())
    }

    return k.account
}

// Create transaction, creates a new and signed transaction, ready for processing
func (k *KeyPair) CreateTx(receiver []byte, value *big.Int, data []string) *Transaction {
    tx := NewTransaction(receiver, value, data)
    tx.Nonce = k.account.Nonce

    // Sign the transaction with the private key in this key chain
    tx.Sign(k.PrivateKey)

    return tx
}

func (k *KeyPair) RlpEncode() []byte {
    return ethutil.EmptyValue().Append(k.PrivateKey).Append(k.PublicKey).Encode()
}

type KeyRing struct {
    keys []*KeyPair
}

func (k *KeyRing) Add(pair *KeyPair) {
    k.keys = append(k.keys, pair)
}

// The public "singleton" keyring
var keyRing *KeyRing

func GetKeyRing(state *State) *KeyRing {
    if keyRing == nil {
        keyRing = &KeyRing{}

        data, _ := ethutil.Config.Db.Get([]byte("KeyRing"))
        it := ethutil.NewValueFromBytes(data).NewIterator()
        for it.Next() {
            v := it.Value()
            keyRing.Add(NewKeyPairFromValue(v))
        }
    }

    return keyRing
}