This repository has been archived by the owner on Mar 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 284
/
convert.go
374 lines (336 loc) · 8.98 KB
/
convert.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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
package cmd
import (
"bufio"
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"os"
"path"
"strings"
"syscall"
"time"
"github.com/OpenBazaar/jsonpb"
"github.com/OpenBazaar/openbazaar-go/core"
"github.com/OpenBazaar/openbazaar-go/ipfs"
"github.com/OpenBazaar/openbazaar-go/pb"
"github.com/OpenBazaar/openbazaar-go/repo"
"github.com/OpenBazaar/openbazaar-go/repo/db"
"github.com/OpenBazaar/wallet-interface"
"github.com/golang/protobuf/proto"
ipfscore "github.com/ipfs/go-ipfs/core"
"github.com/ipfs/go-ipfs/repo/fsrepo"
"golang.org/x/crypto/ssh/terminal"
)
type Convert struct {
Password string `short:"p" long:"password" description:"the encryption password if the database is encrypted"`
DataDir string `short:"d" long:"datadir" description:"specify the data directory to be used"`
Testnet bool `short:"t" long:"testnet" description:"use the test network"`
}
func (x *Convert) Execute(args []string) error {
if len(args) == 0 {
fmt.Fprintf(os.Stderr, "Please specify the cryptocurrency you wish to convert to. Examples:\nopenbazaar-go convert bitcoin\nopenbazaar-go convert bitcoincash\nopenbazaar-go convert zcash /path/to/zcashd\n")
return nil
}
if strings.ToLower(args[0]) == "zcash" && len(args) == 1 {
fmt.Fprintf(os.Stderr, "When converting to zcash please specify the path to the zcash binary. Example:\nopenbazaar-go convert zcash /path/to/zcashd\n")
return nil
}
if !(strings.ToLower(args[0]) == "bitcoin" || strings.ToLower(args[0]) == "bitcoincash" || strings.ToLower(args[0]) == "zcash") {
fmt.Fprintf(os.Stderr, "Unknown currency type: please enter either bitcoin, bitcoincash, or zcash.\n")
return nil
}
var str string
var cfgtype string
var currencyCode string
ct := wallet.Bitcoin
switch strings.ToLower(args[0]) {
case "bitcoin":
str = "Bitcoin"
cfgtype = "spvwallet"
currencyCode = "BTC"
case "bitcoincash":
str = "Bitcoin Cash"
cfgtype = "bitcoincash"
currencyCode = "BCH"
ct = wallet.BitcoinCash
case "zcash":
str = "ZCash"
cfgtype = "zcashd"
currencyCode = "ZEC"
ct = wallet.Zcash
}
if x.Testnet {
currencyCode = "T" + currencyCode
}
reader := bufio.NewReader(os.Stdin)
fmt.Printf("This command will convert your wallet to %s. It will delete any coins you have in your wallet and will prevent you from completing any outstanding orders. Please make sure you have emptied the wallet and completed all your orders before running this command. You will also need to select a new moderator.\n", str)
fmt.Println("Are you sure you want to continue (y/n)?")
yn, _ := reader.ReadString('\n')
if !(strings.ToLower(yn) == "y\n" || strings.ToLower(yn) == "yes\n" || strings.ToLower(yn)[:1] == "y") {
fmt.Println("No changes made")
return nil
}
fmt.Println("Are you REALLY sure (y/n)?")
yn, _ = reader.ReadString('\n')
if !(strings.ToLower(yn) == "y\n" || strings.ToLower(yn) == "yes\n" || strings.ToLower(yn)[:1] == "y") {
fmt.Println("No changes made")
return nil
}
fmt.Println("Working...")
// Set repo path
repoPath, err := repo.GetRepoPath(x.Testnet)
if err != nil {
return err
}
if x.DataDir != "" {
repoPath = x.DataDir
}
// Wipe database tables
var dbPath string
if x.Testnet {
dbPath = path.Join(repoPath, "datastore", "testnet.db")
} else {
dbPath = path.Join(repoPath, "datastore", "mainnet.db")
}
sqlitedb, err := sql.Open("sqlite3", dbPath)
if err != nil {
return err
}
if x.Password != "" {
p := "pragma key='" + x.Password + "';"
sqlitedb.Exec(p)
}
_, err = sqlitedb.Exec("DELETE FROM txns;")
if err != nil {
return err
}
_, err = sqlitedb.Exec("DELETE FROM stxos;")
if err != nil {
return err
}
_, err = sqlitedb.Exec("DELETE FROM utxos;")
if err != nil {
return err
}
_, err = sqlitedb.Exec("DELETE FROM keys;")
if err != nil {
return err
}
// Update coin type in config file
cf, err := ioutil.ReadFile(path.Join(repoPath, "config"))
if err != nil {
return err
}
var cfgIface interface{}
json.Unmarshal(cf, &cfgIface)
cfgObj, ok := cfgIface.(map[string]interface{})
if !ok {
return errors.New("invalid config file")
}
walletIface, ok := cfgObj["Wallet"]
if !ok {
return errors.New("config file missing wallet field")
}
walletCfg, ok := walletIface.(map[string]interface{})
if !ok {
return errors.New("invalid config file")
}
walletCfg["Type"] = cfgtype
if strings.ToLower(args[0]) == "zcash" {
walletCfg["Binary"] = args[1]
}
out, err := json.MarshalIndent(cfgObj, "", " ")
if err != nil {
return err
}
f, err := os.Create(path.Join(repoPath, "config"))
if err != nil {
return err
}
_, err = f.Write(out)
if err != nil {
return err
}
f.Close()
// Update listings with new coin type
creationDate := time.Now()
var sqliteDB *db.SQLiteDatastore
sqliteDB, err = InitializeRepo(repoPath, x.Password, "", x.Testnet, creationDate, ct)
if err != nil && err != repo.ErrRepoExists {
return err
}
// If the database cannot be decrypted, exit
if sqliteDB.Config().IsEncrypted() {
sqliteDB.Close()
fmt.Print("Database is encrypted, enter your password: ")
// nolint:unconvert
bytePassword, _ := terminal.ReadPassword(int(syscall.Stdin))
fmt.Println("")
pw := string(bytePassword)
sqliteDB, err = InitializeRepo(repoPath, pw, "", x.Testnet, time.Now(), ct)
if err != nil && err != repo.ErrRepoExists {
return err
}
if sqliteDB.Config().IsEncrypted() {
PrintError("Invalid password")
os.Exit(3)
}
}
// Get current identity
identityKey, err := sqliteDB.Config().GetIdentityKey()
if err != nil {
PrintError(err.Error())
return err
}
identity, err := ipfs.IdentityFromKey(identityKey)
if err != nil {
return err
}
// IPFS node setup
r, err := fsrepo.Open(repoPath)
if err != nil {
PrintError(err.Error())
return err
}
cctx, cancel := context.WithCancel(context.Background())
defer cancel()
cfg, err := r.Config()
if err != nil {
PrintError(err.Error())
return err
}
cfg.Identity = identity
ncfg := &ipfscore.BuildCfg{
Repo: r,
Online: true,
ExtraOpts: map[string]bool{
"mplex": true,
},
Routing: nil,
}
nd, err := ipfscore.NewNode(cctx, ncfg)
if err != nil {
PrintError(err.Error())
return err
}
files, err := ioutil.ReadDir(path.Join(repoPath, "root", "listings"))
if err != nil {
return err
}
hashes := make(map[string]string)
for _, f := range files {
file, err := ioutil.ReadFile(path.Join(repoPath, "root", "listings", f.Name()))
if err != nil {
return err
}
sl := new(pb.SignedListing)
err = jsonpb.UnmarshalString(string(file), sl)
if err != nil {
return err
}
sl.Listing.Metadata.AcceptedCurrencies = []string{currencyCode}
sl.Listing.Moderators = []string{}
serializedListing, err := proto.Marshal(sl.Listing)
if err != nil {
return err
}
idSig, err := nd.PrivateKey.Sign(serializedListing)
if err != nil {
return err
}
sl.Signature = idSig
m := jsonpb.Marshaler{
EnumsAsInts: false,
EmitDefaults: false,
Indent: " ",
OrigName: false,
}
out, err := m.MarshalToString(sl)
if err != nil {
return err
}
if err := ioutil.WriteFile(path.Join(repoPath, "root", "listings", f.Name()), []byte(out), os.ModePerm); err != nil {
return err
}
h, err := ipfs.GetHashOfFile(nd, path.Join(repoPath, "root", "listings", f.Name()))
if err != nil {
return err
}
hashes[sl.Listing.Slug] = h
}
indexPath := path.Join(repoPath, "root", "listings.json")
indexBytes, err := ioutil.ReadFile(indexPath)
if err != nil {
return err
}
var index []core.ListingData
err = json.Unmarshal(indexBytes, &index)
if err != nil {
return err
}
for i, l := range index {
h, ok := hashes[l.Slug]
if !ok {
return errors.New("malformatted index file")
}
l.Hash = h
index[i] = l
}
// Write it back to file
ifile, err := os.Create(indexPath)
if err != nil {
return err
}
defer ifile.Close()
j, jerr := json.MarshalIndent(index, "", " ")
if jerr != nil {
return jerr
}
_, werr := ifile.Write(j)
if werr != nil {
return werr
}
// Update profile
pro, err := ioutil.ReadFile(path.Join(repoPath, "root", "profile.json"))
if err != nil {
return err
}
profile := new(pb.Profile)
err = jsonpb.UnmarshalString(string(pro), profile)
if err != nil {
return err
}
profile.Currencies = []string{currencyCode}
if profile.ModeratorInfo != nil {
profile.ModeratorInfo.AcceptedCurrencies = []string{currencyCode}
m := jsonpb.Marshaler{
EnumsAsInts: false,
EmitDefaults: false,
Indent: " ",
OrigName: false,
}
out, err := m.MarshalToString(profile)
if err != nil {
return err
}
if err := ioutil.WriteFile(path.Join(repoPath, "root", "profile.json"), []byte(out), os.ModePerm); err != nil {
return err
}
}
nd.Close()
// Remove moderators from settings
settings, err := sqliteDB.Settings().Get()
if err == nil {
settings.StoreModerators = &[]string{}
sqliteDB.Settings().Put(settings)
}
// Remove headers.bin
os.Remove(path.Join(repoPath, "headers.bin"))
// Remove peers.json
os.Remove(path.Join(repoPath, "peers.json"))
fmt.Println("Done")
return nil
}