-
Notifications
You must be signed in to change notification settings - Fork 1
/
cmdline_actions.go
224 lines (210 loc) · 6.28 KB
/
cmdline_actions.go
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
package main
import (
"database/sql"
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"log"
"os"
"path"
"regexp"
"strconv"
"time"
)
var reSqBrackets = regexp.MustCompile(`\[.+]\]`)
func showHelp() {
fmt.Println("Usage:", os.Args[0], "<command> [argument...]")
fmt.Println("Available commands:")
fmt.Println("\thelp\t\tShows this help message.")
fmt.Println("\tcreatewallet\tCreates a new wallet file. Expected arguments: filename wallet_name password.")
fmt.Println("\tcreatekey\tCreates a new key in the current wallet (", path.Join(*dataDir, *walletFileName), "). Expected arguments: key_name password.")
fmt.Println("\t\t\tNote: key_name is the publisher name when the key gets introduced in the blockchain.")
fmt.Println("\tsignjson\tSigns a JSON document string with the specified key. Expected arguments: key_name password json_document.")
fmt.Println("\tlistkeys\tLists the keys in the current wallet.")
fmt.Println("\tsend\tSends coins in a transactions, with optional JSON document. Expected arguments: from_key password to_key amount [json_document].")
fmt.Println()
fmt.Println("Notes:")
fmt.Println("* If started without a command specified, a blockchain node will be started.")
fmt.Println("* The json_document argument (where applicable) is literally a JSON string.")
}
func processSimpleCmdLineActions() bool {
// Actions which may be done when the blockchain is not yet functional (initialised)
cmd := flag.Arg(0)
if cmd == "createwallet" {
if flag.NArg() != 4 {
fmt.Println("Expecting arguments: filename wallet_name password")
os.Exit(1)
}
filename := flag.Arg(1)
name := flag.Arg(2)
password := flag.Arg(3)
w := Wallet{Name: name, Flags: []string{WalletFlagAES256Keys}}
err := w.createKey("default", password)
if err != nil {
log.Fatalln("Cannot create key:", err)
}
err = w.Save(filename)
if err != nil {
log.Fatal(err)
}
fmt.Println(fmt.Sprintf("Created a key named '%s'", w.Keys[0].Name))
return true
} else if cmd == "createkey" {
if flag.NArg() != 3 {
fmt.Println("Expecting arguments: key_name password")
os.Exit(1)
}
keyName := flag.Arg(1)
keyPassword := flag.Arg(2)
initWallet(false)
err := currentWallet.createKey(keyName, keyPassword)
if err != nil {
log.Fatalln("Cannot create key:", err)
}
err = currentWallet.Save(currentWalletFile)
if err != nil {
log.Fatal(err)
}
fmt.Println(fmt.Sprintf("Created a key named '%s'", currentWallet.Keys[len(currentWallet.Keys)-1].Name))
return true
} else if cmd == "signjson" {
if flag.NArg() != 4 {
fmt.Println("Expecting arguments: key_name password json")
os.Exit(1)
}
keyName := flag.Arg(1)
keyPassword := flag.Arg(2)
jsonToSign := []byte(flag.Arg(3))
initWallet(false)
var ii interface{}
err := json.Unmarshal(jsonToSign, &ii)
if err != nil {
log.Fatal(err)
}
if len(currentWallet.Keys) < 1 {
log.Fatal("No keys in current wallet")
}
found := false
for _, key := range currentWallet.Keys {
if key.Name == keyName {
found = true
err := key.UnlockPrivateKey(keyPassword)
if err != nil {
log.Fatal(err)
}
sig, err := key.SignRaw(jsonToSign)
if err != nil {
log.Fatal(err)
}
fmt.Println(base64.RawURLEncoding.EncodeToString(sig))
fmt.Println(bytesToBytesLiteral(sig))
break
}
}
if !found {
log.Fatal("Cannot find key", keyName)
}
return true
} else if cmd == "listkeys" {
initWallet(false)
if len(currentWallet.Keys) < 1 {
log.Fatal("No keys in current wallet")
}
for _, key := range currentWallet.Keys {
fmt.Println(fmt.Sprintf("%-25s %s %v %v", key.Name, key.Public, key.CreationTime.Format(time.RFC3339), key.Flags))
}
return true
}
return false
}
func processCmdLineActions() bool {
// Actions which require the blockchain to be functional
cmd := flag.Arg(0)
if cmd == "help" {
showHelp()
os.Exit(0)
} else if cmd == "send" {
if len(currentWallet.Keys) < 1 {
log.Fatal("No keys in current wallet")
}
if flag.NArg() < 5 {
fmt.Println("Expecting arguments: from_key password to_key amount [json_document]")
os.Exit(1)
}
fromKeyStr := flag.Arg(1)
fromKeyPassword := flag.Arg(2)
toKeyStr := flag.Arg(3)
amountStr := flag.Arg(4)
jsonDoc := flag.Arg(5) // optional
var fromKey *WalletKey
for kid, key := range currentWallet.Keys {
if key.Name == fromKeyStr {
fromKeyStr = key.Public
}
if key.Name == toKeyStr {
toKeyStr = key.Public
}
if key.Public == fromKeyStr {
fromKey = &(currentWallet.Keys[kid])
}
}
if fromKey == nil {
fmt.Println("The from_key argument must be in the current wallet")
os.Exit(1)
}
if fromKeyStr == toKeyStr {
fmt.Println("Warning: sending a tx from and to the same address")
}
f, err := strconv.ParseFloat(amountStr, 32)
if err != nil {
fmt.Println("Invalid number:", amountStr, err.Error())
os.Exit(1)
}
if f < 0 {
fmt.Println("Cannot send negative amounts")
os.Exit(1)
}
amountInt := uint64(f * OneCoin)
var doc PublishedData
if jsonDoc != "" && json.Unmarshal([]byte(jsonDoc), &doc) != nil {
fmt.Println("Invalid JSON document:", jsonDoc)
os.Exit(1)
}
newNonce := uint64(1)
dbtx, err := db.Begin()
if err != nil {
log.Fatal(err)
}
defer dbtx.Commit()
states, err := dbGetStates(dbtx, []string{toKeyStr, fromKeyStr})
if err != nil && err != sql.ErrNoRows {
log.Fatal(err)
}
// fmt.Println(jsonifyWhatever(states))
if states[fromKeyStr] == nil {
// No "from" address in state database, nothing to send!
fmt.Println("No state to send from:", fromKeyStr)
os.Exit(1)
}
newNonce = states[fromKeyStr].Nonce + 1
tx := Tx{Data: doc, SigningPubKey: fromKeyStr, PubKeyNonce: newNonce, Version: CurrentTxVersion, Outputs: []TxOutput{TxOutput{PubKey: toKeyStr, Amount: amountInt}}}
txJSONBytes := jsonifyWhateverToBytes(tx)
err = fromKey.UnlockPrivateKey(fromKeyPassword)
if err != nil {
log.Fatal(err)
}
sig, err := fromKey.SignRaw(txJSONBytes)
if err != nil {
log.Fatal(err)
}
strSig := mustEncodeBase64URL(sig)
btx := BlockTransaction{TxHash: getTxHashStr(txJSONBytes), TxData: string(txJSONBytes), Signature: strSig}
_, err = dbtx.Exec("INSERT INTO utx(hash, ts, tx) VALUES (?, ?, ?)", btx.TxHash, time.Now().Unix(), jsonifyWhatever(btx))
if err != nil {
log.Fatal(err)
}
return true
}
return false
}