-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmobile_interface.go
600 lines (462 loc) · 14.2 KB
/
mobile_interface.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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
package panthalassa
import (
"context"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"time"
api "github.com/Bit-Nation/panthalassa/api"
apiPB "github.com/Bit-Nation/panthalassa/api/pb"
backend "github.com/Bit-Nation/panthalassa/backend"
chat "github.com/Bit-Nation/panthalassa/chat"
contacts "github.com/Bit-Nation/panthalassa/contacts"
dapp "github.com/Bit-Nation/panthalassa/dapp"
dAppReg "github.com/Bit-Nation/panthalassa/dapp/registry"
db "github.com/Bit-Nation/panthalassa/db"
documents "github.com/Bit-Nation/panthalassa/documents"
dyncall "github.com/Bit-Nation/panthalassa/dyncall"
keyManager "github.com/Bit-Nation/panthalassa/keyManager"
p2p "github.com/Bit-Nation/panthalassa/p2p"
profile "github.com/Bit-Nation/panthalassa/profile"
queue "github.com/Bit-Nation/panthalassa/queue"
uiapi "github.com/Bit-Nation/panthalassa/uiapi"
storm "github.com/asdine/storm"
common "github.com/ethereum/go-ethereum/common"
ethclient "github.com/ethereum/go-ethereum/ethclient"
proto "github.com/golang/protobuf/proto"
log "github.com/ipfs/go-log"
ma "github.com/multiformats/go-multiaddr"
bolt "go.etcd.io/bbolt"
)
var panthalassaInstance *Panthalassa
var logger = log.Logger("panthalassa")
type UpStream interface {
Send(data string)
}
type StartConfig struct {
EncryptedKeyManager string `json:"encrypted_key_manager"`
SignedProfile string `json:"signed_profile"`
EthWsEndpoint string `json:"eth_ws_endpoint"`
EnableDebugging bool `json:"enable_debugging"`
PrivChatEndpoint string `json:"private_chat_endpoint"`
PrivChatBearerToken string `json:"private_chat_bearer_token"`
}
// create a new panthalassa instance
func start(dbDir string, km *keyManager.KeyManager, config StartConfig, client, uiUpstream UpStream) error {
if config.EnableDebugging {
log.SetDebugLogging()
}
//Exit if instance was already created and not stopped
if panthalassaInstance != nil {
return errors.New("call stop first in order to create a new panthalassa instance")
}
// device api
deviceApi := api.New(client)
km.Api = deviceApi
// create p2p network
p2pNetwork, err := p2p.New()
if err != nil {
return err
}
// open database
dbPath, err := db.KMToDBPath(dbDir, km)
if err != nil {
return err
}
// migrate
migrations := []db.Migration{
&db.BoltToStormMigration{
Km: km,
},
}
if err := db.Migrate(dbPath, migrations); err != nil {
return err
}
dbInstance, err := storm.Open(dbPath, storm.BoltOptions(0644, &bolt.Options{Timeout: time.Second}))
if err != nil {
return err
}
// create signed pre key storage
signedPreKeyStorage := db.NewBoltSignedPreKeyStorage(dbInstance, km)
// create backend
trans := backend.NewWSTransport(config.PrivChatEndpoint, config.PrivChatBearerToken, km)
backend, err := backend.NewBackend(trans, km, signedPreKeyStorage)
if err != nil {
return err
}
// ui api
uiApi := uiapi.New(uiUpstream)
// open message storage
chatStorage := db.NewChatStorage(dbInstance, []func(db.MessagePersistedEvent){}, km)
// queue instance
jobStorage := queue.NewStorage(dbInstance)
q := queue.New(jobStorage, 250, 4)
// chat
chatInstance, err := chat.NewChat(chat.Config{
ChatStorage: chatStorage,
Backend: backend,
SharedSecretDB: db.NewBoltSharedSecretStorage(dbInstance, km),
KM: km,
DRKeyStorage: db.NewBoltDRKeyStorage(dbInstance, km),
SignedPreKeyStorage: signedPreKeyStorage,
OneTimePreKeyStorage: db.NewBoltOneTimePreKeyStorage(dbInstance, km),
UserStorage: db.NewBoltUserStorage(dbInstance),
UiApi: uiApi,
Queue: q,
})
if err != nil {
return err
}
// dApp storage
dAppStorage := dapp.NewDAppStorage(dbInstance, uiApi)
// dApp registry
dAppRegistry, err := dAppReg.NewDAppRegistry(p2pNetwork.Host, dAppReg.Config{
EthWSEndpoint: config.EthWsEndpoint,
}, deviceApi, km, dAppStorage, chatStorage)
if err != nil {
return err
}
// dyncall registry
dcr := dyncall.New()
// register document related calls
docStorage := documents.NewStorage(dbInstance, km)
if err := RegisterDocumentCalls(dcr, docStorage, km); err != nil {
return err
}
ethClient, err := ethclient.Dial(config.EthWsEndpoint)
if err != nil {
return err
}
networkID, err := ethClient.NetworkID(context.Background())
if err != nil {
return err
}
var notaryMultiAddr common.Address
if networkID.Int64() == int64(4) {
notaryMultiAddr = common.HexToAddress("0xe4d2032fdda10d4e6f483e2dea6857abc0e3cbf8")
} else if networkID.Int64() == int64(1) {
notaryMultiAddr = common.HexToAddress("0xb54d5dcbadefe0838b3fb4cae3aa071c553aa297")
} else {
return errors.New("no notary available for network")
}
// rinkeby addresses
// @TODO Figure out if the notaryMultiAddr override of the if conditional above was done on purpose
//notaryMultiAddr = common.HexToAddress("0xe4d2032fdda10d4e6f483e2dea6857abc0e3cbf8")
notaryContract, err := documents.NewNotaryMulti(notaryMultiAddr, ethClient)
if err != nil {
return err
}
notariseCall := documents.NewDocumentNotariseCall(docStorage, km, notaryContract)
if err := dcr.Register(notariseCall); err != nil {
return err
}
// register contract calls
if err := RegisterContactCalls(dcr, dbInstance); err != nil {
return err
}
//Create panthalassa instance
panthalassaInstance = &Panthalassa{
km: km,
upStream: client,
api: deviceApi,
p2p: p2pNetwork,
dAppReg: dAppRegistry,
chat: chatInstance,
db: dbInstance,
dAppStorage: dAppStorage,
dyncall: dcr,
chatDB: chatStorage,
}
return nil
}
func RegisterDocumentCalls(dcr *dyncall.Registry, docStorage *documents.Storage, km *keyManager.KeyManager) error {
// register document all call
allCall := documents.NewDocumentAllCall(docStorage)
if err := dcr.Register(allCall); err != nil {
return err
}
// register create document call
createCall := documents.NewDocumentCreateCall(docStorage)
if err := dcr.Register(createCall); err != nil {
return err
}
// register document update call
updateCall := documents.NewDocumentUpdateCall(docStorage)
if err := dcr.Register(updateCall); err != nil {
return err
}
// register document delete call
deleteCall := documents.NewDocumentDeleteCall(docStorage)
if err := dcr.Register(deleteCall); err != nil {
return err
}
return nil
}
func RegisterContactCalls(dcr *dyncall.Registry, dbInstance *storm.DB) error {
contactStorage := contacts.NewStorage(dbInstance)
// register contacts all call
allCall := contacts.NewContactAllCall(contactStorage)
if err := dcr.Register(allCall); err != nil {
return err
}
// register contact create call
createCall := contacts.NewContactCreateCall(contactStorage)
if err := dcr.Register(createCall); err != nil {
return err
}
return nil
}
// start panthalassa
func Start(dbDir, config, password string, client, uiUpstream UpStream) error {
// unmarshal config
var c StartConfig
if err := json.Unmarshal([]byte(config), &c); err != nil {
return err
}
store, err := keyManager.UnmarshalStore([]byte(c.EncryptedKeyManager))
if err != nil {
return err
}
// open key manager with password
km, err := keyManager.OpenWithPassword(store, password)
if err != nil {
return err
}
return start(dbDir, km, c, client, uiUpstream)
}
// create a new panthalassa instance with the mnemonic
func StartFromMnemonic(dbDir, config, mnemonic string, client, uiUpstream UpStream) error {
// unmarshal config
var c StartConfig
if err := json.Unmarshal([]byte(config), &c); err != nil {
return err
}
store, err := keyManager.UnmarshalStore([]byte(c.EncryptedKeyManager))
if err != nil {
return err
}
// create key manager
km, err := keyManager.OpenWithMnemonic(store, mnemonic)
if err != nil {
return err
}
// create panthalassa instance
return start(dbDir, km, c, client, uiUpstream)
}
//Eth Private key
func EthPrivateKey() (string, error) {
if panthalassaInstance == nil {
return "", errors.New("you have to start panthalassa")
}
return panthalassaInstance.km.GetEthereumPrivateKey()
}
func EthAddress() (string, error) {
if panthalassaInstance == nil {
return "", errors.New("you have to start panthalassa")
}
return panthalassaInstance.km.GetEthereumAddress()
}
func SendResponse(id string, data string, responseError string, timeout int) error {
if panthalassaInstance == nil {
return errors.New("you have to start panthalassa")
}
dataBytes, decodingError := base64.StdEncoding.DecodeString(data)
if decodingError != nil {
return decodingError
}
resp := &apiPB.Response{}
if err := proto.Unmarshal(dataBytes, resp); err != nil {
return err
}
var err error
if responseError != "" {
err = errors.New(responseError)
}
return panthalassaInstance.api.Respond(id, resp, err, time.Duration(timeout)*time.Second)
}
//Export the current account store with given password
func ExportAccountStore(pw, pwConfirm string) (string, error) {
if panthalassaInstance == nil {
return "", errors.New("you have to start panthalassa")
}
return panthalassaInstance.Export(pw, pwConfirm)
}
func IdentityPublicKey() (string, error) {
if panthalassaInstance == nil {
return "", errors.New("you have to start panthalassa")
}
return panthalassaInstance.km.IdentityPublicKey()
}
func GetMnemonic() (string, error) {
if panthalassaInstance == nil {
return "", errors.New("you have to start panthalassa")
}
return panthalassaInstance.km.GetMnemonic().String(), nil
}
func SignProfile(name, location, image string) (string, error) {
if panthalassaInstance == nil {
return "", errors.New("you have to start panthalassa")
}
// sign profile
p, err := profile.SignProfile(name, location, image, *panthalassaInstance.km)
if err != nil {
return "", err
}
// export profile to protobuf
pp, err := p.ToProtobuf()
if err != nil {
return "", err
}
// marshal protobuf profile
rawProfile, err := proto.Marshal(pp)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(rawProfile), nil
}
//Stop panthalassa
func Stop() error {
//Exit if not started
if panthalassaInstance == nil {
return errors.New("you have to start panthalassa in order to stop it")
}
//Stop panthalassa
err := panthalassaInstance.Stop()
if err != nil {
//Reset singleton
panthalassaInstance = nil
return err
}
//Reset singleton
panthalassaInstance = nil
return nil
}
// fetch the identity public key of the
func GetIdentityPublicKey() (string, error) {
//Exit if not started
if panthalassaInstance == nil {
return "", errors.New("you have to start panthalassa first")
}
return panthalassaInstance.km.IdentityPublicKey()
}
// connect the host to DApp development server
func ConnectToDAppDevHost(address string) error {
//Exit if not started
if panthalassaInstance == nil {
return errors.New("you have to start panthalassa first")
}
maAddr, err := ma.NewMultiaddr(address)
if err != nil {
return err
}
return panthalassaInstance.dAppReg.ConnectDevelopmentServer(maAddr)
}
func OpenDApp(id, context string) error {
//Exit if not started
if panthalassaInstance == nil {
return errors.New("you have to start panthalassa first")
}
// decode public key
dAppSigningKey, err := hex.DecodeString(id)
if err != nil {
return err
}
if len(dAppSigningKey) != 32 {
return errors.New("invalid DApp signing key")
}
return panthalassaInstance.dAppReg.OpenDApp(dAppSigningKey, context)
}
func StartDApp(dAppSingingKeyStr string, timeout int) error {
//Exit if not started
if panthalassaInstance == nil {
return errors.New("you have to start panthalassa first")
}
// decode singing key
dAppSigningKey, err := hex.DecodeString(dAppSingingKeyStr)
if err != nil {
return err
}
// signing key must be 32 bytes long since it's an ed25519 pub key
if len(dAppSigningKey) != 32 {
return errors.New("DApp singing key must be 32 bytes long")
}
return panthalassaInstance.dAppReg.StartDApp(dAppSigningKey, time.Second*time.Duration(timeout))
}
func RenderMessage(signingKey, payload string) (string, error) {
//Exit if not started
if panthalassaInstance == nil {
return "", errors.New("you have to start panthalassa first")
}
// decode signing key
dAppSigningKey, err := hex.DecodeString(signingKey)
if err != nil {
return "", err
}
if len(dAppSigningKey) != 32 {
return "", errors.New("dapp signign key must be 32 bytes long")
}
return panthalassaInstance.dAppReg.RenderMessage(dAppSigningKey, payload)
}
func CallDAppFunction(signingKey string, id int, args string) error {
// make sure we get an uint value
if id < 0 {
return errors.New("got negative number but need uint")
}
//Exit if not started
if panthalassaInstance == nil {
return errors.New("you have to start panthalassa first")
}
// decode signing key
dAppSigningKey, err := hex.DecodeString(signingKey)
if err != nil {
return err
}
if len(dAppSigningKey) != 32 {
return errors.New("dapp signign key must be 32 bytes long")
}
return panthalassaInstance.dAppReg.CallFunction(dAppSigningKey, uint(id), args)
}
func StopDApp(dAppSingingKeyStr string) error {
if panthalassaInstance == nil {
return errors.New("you have to start panthalassa first")
}
// decode singing key
dAppSigningKey, err := hex.DecodeString(dAppSingingKeyStr)
if err != nil {
return err
}
// signing key must be 32 bytes long since it's and ed25519 pub key
if len(dAppSigningKey) != 32 {
return errors.New("DApp singing key must be 32 bytes long")
}
return panthalassaInstance.dAppReg.ShutDown(dAppSigningKey)
}
func DApps() (string, error) {
if panthalassaInstance == nil {
return "", errors.New("you have to start panthalassa first")
}
// fetch dApps
dApps, err := panthalassaInstance.dAppStorage.All()
if err != nil {
return "", err
}
// marshal dapps
rawDApps, err := json.Marshal(dApps)
return string(rawDApps), err
}
func Call(command, payload string) (string, error) {
var goPayload map[string]interface{}
if err := json.Unmarshal([]byte(payload), &goPayload); err != nil {
return "", err
}
if panthalassaInstance == nil {
return "", errors.New("you have to start panthalassa first")
}
res, err := panthalassaInstance.dyncall.Call(command, goPayload)
if err != nil {
return "", err
}
response, err := json.Marshal(res)
return string(response), err
}