-
Notifications
You must be signed in to change notification settings - Fork 2
/
driver.html
1317 lines (1302 loc) · 40.4 KB
/
driver.html
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta httpEquiv="Content-Type" content="text/html; charset=utf-8" />
<title>Offer a Ride | Bullrun</title>
<link rel="icon" href="images/icons/favicon.svg" type="image/svg+xml" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link rel="stylesheet" href="css/styles.css" />
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Inter:wght@200;300;400;500;600;700&display=swap"
/>
<script src="https://bitcoincore.tech/apps/bitcoinjs-ui/lib/bitcoinjs-lib.js"></script>
<script src="https://bundle.run/[email protected]"></script>
<script src="https://bundle.run/[email protected]"></script>
<script src="https://bundle.run/[email protected]"></script>
<script src="https://bundle.run/[email protected]"></script>
<script src="https://bundle.run/[email protected]"></script>
<script>
var lndendpoint = ''
var lndmacaroon = ''
</script>
<script>
function computeRawPrivkey(node) {
return bitcoinjs.ECPair.fromPrivateKey(node.privateKey, {
network: bitcoinjs.networks.mainnet,
})
}
</script>
<script>
function getPrivkeyHex(backupwords, path, index) {
var seed = bip39.mnemonicToSeedSync(backupwords)
var node = bip32.fromSeed(seed)
var path = 'm/' + path + '/' + index
var root = node
var child = root.derivePath(path)
return computeRawPrivkey(child)
}
</script>
<script>
function toHexString(byteArray) {
return Array.from(byteArray, function (byte) {
return ('0' + (byte & 0xff).toString(16)).slice(-2)
}).join('')
}
</script>
<script>
var backupwords = bip39.generateMnemonic()
var path = 0
var index = 1
var privKey = getPrivkeyHex(backupwords, path, index)
privKey = privKey.__D.toString('hex')
var pubKey = nobleSecp256k1.getPublicKey(privKey, true)
var pubKeyMinus2 = pubKey.substring(2)
</script>
<script>
var options
options = {
enableHighAccuracy: true,
timeout: 15000,
maximumAge: 5000,
}
function error(err) {
console.warn('ERROR( ' + err.code + ' ): ' + err.message)
}
function getLocation() {
if (navigator.geolocation) {
id = navigator.geolocation.watchPosition(
watchUsersPosition,
error,
options
)
} else {
console.error(
'Geolocation is not supported by this browser.'
)
}
}
var from = {}
var to = {}
var olddist = ''
var finalized = false
var offeramt = ''
function getDistance(from, to) {
return (from.distanceTo(to).toFixed(0) / 1609.344).toFixed(3)
}
function watchUsersPosition(position) {
//update a sessionstorage variable every ten seconds with the driver's position
var location = {
lat: position.coords.latitude,
lng: position.coords.longitude,
}
location = JSON.stringify(location)
sessionStorage['location'] = location
document.getElementById('getting-location').style.display =
'none'
document.getElementById('content').style.display = 'block'
var riderlocation = JSON.parse(sessionStorage['rider-location'])
var riderobj = L.marker(riderlocation)
var driver = JSON.parse(location)
var driverobj = L.marker(driver)
var dist_to_rider = getDistance(
driverobj.getLatLng(),
riderobj.getLatLng()
)
if (dist_to_rider < 0.042) {
sessionStorage['i-picked-up-my-rider'] = true
}
}
sessionStorage['privkey'] = buffer.Buffer.from(
nobleSecp256k1.utils.randomPrivateKey()
).toString('hex')
var riderlocation = { lat: 0, lng: 0 }
riderlocation = JSON.stringify(riderlocation)
sessionStorage['rider-location'] = riderlocation
getLocation()
</script>
<script>
function convertHMS(value) {
const sec = parseInt(value, 10); // convert value to number if it's string
let hours = Math.floor(sec / 3600); // get hours
let minutes = Math.floor((sec - (hours * 3600)) / 60); // get minutes
let seconds = sec - (hours * 3600) - (minutes * 60); // get seconds
// add 0 if value < 10; Example: 2 => 02
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
return minutes+' m '+seconds+' s'; // Return is MM m SS s
}
</script>
<script>
function normalizeRelayURL(e) {
let [t, ...r] = e.trim().split('?')
return (
'http' === t.slice(0, 4) && (t = 'ws' + t.slice(4)),
'ws' !== t.slice(0, 2) && (t = 'wss://' + t),
t.length && '/' === t[t.length - 1] && (t = t.slice(0, -1)),
[t, ...r].join('?')
)
}
var relay = 'wss://relay.damus.io'
relay = normalizeRelayURL(relay)
var socket = new WebSocket(relay)
var filter = {
'#p': [pubKeyMinus2],
}
var subscription = ['REQ', 'get-self-references', filter]
subscription = JSON.stringify(subscription)
//sessionStorage['selfsubscription'] = subscription
setTimeout(function () {
socket.send(subscription)
}, 1000)
var filter = {
kinds: [20060],
}
var subscription2 = ['REQ', 'get-kind-sixty', filter]
subscription2 = JSON.stringify(subscription2)
//sessionStorage['kindsixtysub'] = subscription2
setTimeout(function () {
socket.send(subscription2)
}, 1000)
function subscribe(pubkey) {
var filter = {
authors: [pubkey],
}
var subscription = ['REQ', 'my-sub', filter]
subscription = JSON.stringify(subscription)
//sessionStorage.subscription = subscription
socket.send(subscription)
}
socket.addEventListener('open', function (event) {
console.log('connected to nostr relay ' + relay)
})
// Listen for messages
socket.addEventListener('message', function (event) {
var event = JSON.parse(event.data)
if (event[2] && event[2].kind == 20060) {
var eventContent = event[2]
? JSON.parse(event[2].content)
: null
var recentRequests = []
if (eventContent) {
console.log('expires:', eventContent.expires)
console.log('now:', Math.floor( Date.now() / 1000 ) )
}
var i = -1;
if (eventContent) {
i = i + 1;
recentRequests.push(eventContent)
var fromobj = L.marker(eventContent.from)
var toobj = L.marker(eventContent.to)
var distance = Number( getDistance( fromobj.getLatLng(), toobj.getLatLng() ) ).toLocaleString(undefined, {
maximumFractionDigits: 1,
})
var numsecs = eventContent.expires - Math.floor( Date.now() / 1000 )
if ( numsecs < 0 ) {numsecs = 0}
var expiry = convertHMS( numsecs )
var contract = JSON.stringify( eventContent );
var div = `<div id="request_${i}">
<div class="request-amount">${eventContent.amount} <br /><span class="sats">sats</span></div>
<div class="request-name">${eventContent.name}</div>
<div class="request-distance">${distance} miles</div>
<div class="request-expiry" data-expires="${eventContent.expires}">${expiry}</div>
<div class="request-button"><button id="${event[2].pubkey}" data-contract='${contract}' onclick='acceptRider( this.getAttribute( "id" ), this.getAttribute( "data-contract" ) )'>Accept</button></div>
</div>`
if ( numsecs > 0 ) {
document.getElementById('request_listings').innerHTML += div
}
}
recentRequests.sort((a, b) => b.expires > a.expires)
console.log('event:', event)
}
if (event[2] && event[2].kind == 4) {
var i
for (i = 0; i < event[2].tags.length; i++) {
if (event[2].tags[i] && event[2].tags[i][1]) {
var recipient = event[2].tags[i][1]
if (recipient == pubKeyMinus2) {
var decrypted_message = decrypt(
privKey,
event[2].pubkey,
event[2].content
)
console.log(
decrypted_message +
' (sent privately by ' +
event[2].pubkey +
')'
)
decideMessageTypeAndNextSteps(
decrypted_message,
event[2].pubkey
)
} else if (event[2].pubkey == pubKeyMinus2) {
console.log(
decrypt(
privKey,
recipient,
event[2].content
) +
' (sent privately by ' +
event[2].pubkey +
')'
)
}
}
}
} else if (event[2] && event[2].kind == 1) {
console.log(
event[2].content +
' (sent publicly by ' +
event[2].pubkey +
')'
)
} else if (event[2] && event[2].kind == 20060) {
var json = JSON.parse(event[2].content)
var expires = json['expires']
var current_timestamp = Math.floor(
new Date().getTime() / 1000
)
if (Number(current_timestamp) >= Number(expires)) {
return
}
var type = json['type']
if (type != 'offer') {
return
}
console.log(
"your ride id (save this, you'll need it in case of a dispute):",
event[2].id
)
var from = json['from']
var fromobj = L.marker(from)
var to = json['to']
var toobj = L.marker(to)
var amount = json['amount']
var name = json['name']
console.log(event[2].content, event[2].id, event[2].pubkey)
/*
var i_want_to_pick_up_the_rider = confirm(
'Click okay if you want to pick up ' +
name +
' and take them ' +
getDistance(
fromobj.getLatLng(),
toobj.getLatLng()
) +
' miles away for ' +
amount +
' sats'
)
if (!i_want_to_pick_up_the_rider) {
return
}
//if the driver says they want to pick up the rider, make them send the rider a dm with a pubkey that the voucher should be locked to, then -- if the rider sends back a voucher and its ownership is confirmed pending a second preimage (and if it's funded) -- give the driver this link so they can go get the rider: var url = "https://maps.google.com/?q=" + from[ "lat" ] + "," + from[ "lng" ]
acceptRider( event[2].pubkey, JSON.stringify( json ) );
//the rider's app should automatically send the second preimage to the driver if their app says they get within 100 feet of their destination, or they can show them the preimage they need manually
*/
}
})
function makePrivateNote(note, recipientpubkey) {
console.log("note: '" + note + "'")
var now = Math.floor(new Date().getTime() / 1000)
console.log(now)
var privatenote = encrypt(privKey, recipientpubkey, note)
var newevent = [
0,
pubKeyMinus2,
now,
4,
[['p', recipientpubkey]],
privatenote,
]
var message = JSON.stringify(newevent)
console.log("message: '" + message + "'")
var msghash = bitcoinjs.crypto.sha256(message).toString('hex')
console.log("msghash: '" + msghash + "'")
nobleSecp256k1.schnorr.sign(msghash, privKey).then((value) => {
sig = value
console.log('the sig is:', sig)
nobleSecp256k1.schnorr
.verify(sig, msghash, pubKeyMinus2)
.then((value) => {
console.log(
'this should say true if the signature is valid for the above pubkey over the message',
value
)
if (value) {
var fullevent = {
id: msghash,
pubkey: pubKeyMinus2,
created_at: now,
kind: 4,
tags: [['p', recipientpubkey]],
content: privatenote,
sig: sig,
}
var sendable = ['EVENT', fullevent]
sessionStorage.sendable =
JSON.stringify(sendable)
socket.send(
'["EVENT",' +
JSON.stringify(
JSON.parse(
sessionStorage.sendable
)[1]
) +
']'
)
}
})
})
}
function encrypt(privkey, pubkey, text) {
console.log(
'recipient pubkey (because I keep getting an error that it is not real):',
pubkey
)
var key = nobleSecp256k1
.getSharedSecret(privkey, '02' + pubkey, true)
.substring(2)
var iv = window.crypto.getRandomValues(new Uint8Array(16))
var cipher = browserifyCipher.createCipheriv(
'aes-256-cbc',
buffer.Buffer.from(key, 'hex'),
iv
)
var encryptedMessage = cipher.update(text, 'utf8', 'base64')
emsg = encryptedMessage + cipher.final('base64')
return (
emsg +
'?iv=' +
buffer.Buffer.from(iv.buffer).toString('base64')
)
}
function decrypt(privkey, pubkey, ciphertext) {
var [emsg, iv] = ciphertext.split('?iv=')
var key = nobleSecp256k1
.getSharedSecret(privkey, '02' + pubkey, true)
.substring(2)
var decipher = browserifyCipher.createDecipheriv(
'aes-256-cbc',
buffer.Buffer.from(key, 'hex'),
buffer.Buffer.from(iv, 'base64')
)
var decryptedMessage = decipher.update(emsg, 'base64')
dmsg = decryptedMessage + decipher.final('utf8')
return dmsg
}
</script>
<script>
function acceptRider( rider_pubkey, contract ) {
sessionStorage['current-contract'] = contract
var message = {}
message['type'] = 'acceptance'
message['name'] = sessionStorage['driver-name']
message['vehicle'] = sessionStorage['vehicle-description']
message['coordinates'] = JSON.parse(
sessionStorage['location']
)
sessionStorage['rider'] = rider_pubkey
var driver_privkey = sessionStorage['privkey']
var pubkey = nobleSecp256k1.getPublicKey(
driver_privkey,
true
)
message['pubkey'] = pubkey
message = JSON.stringify(message)
makePrivateNote(message, rider_pubkey)
}
</script>
<script type="text/javascript">
var link = document.createElement('link')
link.rel = 'stylesheet'
link.href = 'https://unpkg.com/[email protected]/dist/leaflet.css'
link.integrity =
'sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=='
link.setAttribute('crossorigin', '')
document.getElementsByTagName('head')[0].appendChild(link)
</script>
<script>
function setExpiries() {
var expiryboxes = document.getElementsByClassName( "request-expiry" );
var i; for ( i=0; i<expiryboxes.length; i++ ) {
var prevexpires = expiryboxes[ i ].getAttribute( "data-expires" );
var now = Math.floor( Date.now() / 1000 );
var numsecs = prevexpires - now;
if ( numsecs < 0 ) {numsecs = 0;expiryboxes[ i ].parentElement.style.display = 'none'}
var expiry = convertHMS( numsecs )
expiryboxes[ i ].innerHTML = expiry;
}
setTimeout( function() {setExpiries();}, 1000 );
}
setExpiries();
</script>
<script
src="https://unpkg.com/[email protected]/dist/leaflet.js"
integrity="sha512-GffPMF3RvMeYyc1LWMHtK8EbPv0iNZ8/oTtHPx9/cc2ILxQ+u905qIwdpULaqDkyBKgOaB57QTMg7ztg8Jm2Og=="
crossorigin=""
></script>
</head>
<body>
<script>
var template1 = `function script( params ) {var signature = params[ 0 ];return nobleSecp256k1.verify( signature, @challenge@, @recipient@ );}`
var template1hash = bitcoinjs.crypto
.sha256(template1)
.toString('hex')
function reviseTemplate1(challenge, pubkey) {
var revisedscript = template1.replace(
/@.*?(@)/,
'"' + challenge + '"'
)
revisedscript = revisedscript.replace(
/@.*?(@)/,
'"' + pubkey + '"'
)
return revisedscript
}
var template2 = `function script( params ) {var signature = params[ 0 ];var preimage = params[ 1 ];if ( bitcoinjs.crypto.sha256( Buffer.from( preimage, "hex" ) ).toString( "hex" ) == @hash@ ) {return nobleSecp256k1.verify( signature, @challenge@, @recipient@ );}}`
var template2hash = bitcoinjs.crypto
.sha256(template2)
.toString('hex')
function reviseTemplate2(hash, challenge, pubkey) {
var revisedscript = template2.replace(
/@.*?(@)/,
'"' + hash + '"'
)
revisedscript = revisedscript.replace(
/@.*?(@)/,
'"' + challenge + '"'
)
revisedscript = revisedscript.replace(
/@.*?(@)/,
'"' + pubkey + '"'
)
return revisedscript
}
</script>
<header id="site_header">
<div id="site-branding">
<h1 class="site-title"><a href="driver.html">Bullrun</a></h1>
</div>
<div id="getting-location">
<p>Getting your location...</p>
</div>
</header>
<main id="site_content">
<div id="content" style="display: none">
<div
id="error banner"
style="
background-color: red;
color: white;
font-weight: bold;
padding: 5px;
font-family: sans-serif;
display: none;
"
></div>
<div id="driver_info">
<p>
Name: <span id="driver_name"></span><br />
Vehicle: <span id="driver_vehicle"></span>
</p>
<p>
Not you?
<a
onclick="sessionStorage.clear();window.location.reload()"
>Change Driver</a
>
</p>
</div>
<div id="endpoint-and-macaroon-box">
<h2>Node Connection</h2>
<p>
Get your rest api endpoint and your invoice macaroon
from your Umbrel, MyNode, Voltage, or other node.
</p>
<form id="node_connection_form">
<div class="form-field-wrapper">
<label for="endpoint">Rest API Endpoint</label>
<input
type="text"
id="endpoint"
name="endpoint"
placeholder="https://tor.onion:8080"
/>
</div>
<div class="form-field-wrapper">
<label for="macaroon">Invoice Macaroon</label>
<input type="text" id="macaroon" name="macaroon" />
</div>
<button type="button" id="set-endpoint-and-macaroon">
Submit
</button>
</form>
</div>
<div
id="instructions"
class="highlight-box success"
style="display: none"
></div>
<div id="ride_requests">
<h2>Recent Requests</h2>
<div id="request_listings"></div>
</div>
</div>
</main>
<footer id="site_footer">
<p>
<a
href="https://github.com/supertestnet/bullrun"
target="_blank"
rel="noopener noreferrer"
>Bullrun on Github</a
>
</p>
</footer>
<script>
//document.getElementById( "terminal instructions" ).innerText = "lncli addinvoice --amt " + amount + " --preimage " + preimage;
</script>
<script>
async function provePendingOwnership(voucherhex = '') {
if (!voucherhex || voucherhex == '') {
var voucher = JSON.parse(
buffer.Buffer.from(
document.getElementById('voucher').value,
'hex'
).toString()
)
} else {
var voucher = JSON.parse(
buffer.Buffer.from(voucherhex, 'hex').toString()
)
}
var preimage = voucher['preimage']
var voucherid = voucher['voucherid']
var querykey = voucher['querykey']
var amount = voucher['amount']
var escrow = voucher['escrow']
var lockinghash_according_to_user = voucher['lockinghash']
var templatehash = voucher['templatehash']
if (templatehash == template2hash) {
var driver_privkey = sessionStorage['privkey']
var challenge =
'9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08'
var pubkey = nobleSecp256k1.getPublicKey(
driver_privkey,
true
)
var script = reviseTemplate2(
lockinghash_according_to_user,
challenge,
pubkey
)
console.log(script)
var scriptinhex = buffer.Buffer.from(script).toString('hex')
console.log(scriptinhex)
var senderscripthash = bitcoinjs.crypto
.sha256(script)
.toString('hex')
var voucherinfofromescrow = await getVoucherInfoFromEscrow(
voucherid
)
voucherinfofromescrow = JSON.parse(voucherinfofromescrow)
console.log('the info returned is', voucherinfofromescrow)
if (voucherinfofromescrow['status'] != 'ACCEPTED') {
//console.error( "Oh no! The voucher is not funded, its status is", voucherinfofromescrow[ "status" ] );
//return false;
}
var escrowscripthash = voucherinfofromescrow['scripthash']
console.log(
'script hashes, first from the escrow, then from the sender:',
escrowscripthash,
senderscripthash
)
var senderpmthash = bitcoinjs.crypto
.sha256(buffer.Buffer.from(preimage, 'hex'))
.toString('hex')
var escrowpmthash = voucherinfofromescrow['pmthash']
var senderamount = Number(amount)
var escrowamount = Number(voucherinfofromescrow['amount'])
console.log(
'the script hashes match, right?',
senderscripthash == escrowscripthash
)
if (senderscripthash != escrowscripthash) {
return false
}
console.log(
'the payment hashes match, right?',
senderpmthash == escrowpmthash
)
if (senderpmthash != escrowpmthash) {
return false
}
console.log(
'the amounts match, right?',
senderamount == escrowamount
)
if (senderamount != escrowamount) {
return false
}
console.log(
'I now know that I will be the owner if I get the second preimage and it hashes to this:',
lockinghash_according_to_user
)
return true
}
}
</script>
<script>
async function proveFullOwnership(
voucherhex = '',
second_preimage = ''
) {
if (!voucherhex || voucherhex == '') {
var voucher = JSON.parse(
buffer.Buffer.from(
document.getElementById('voucher').value,
'hex'
).toString()
)
} else {
var voucher = JSON.parse(
buffer.Buffer.from(voucherhex, 'hex').toString()
)
}
if (!second_preimage || second_preimage == '') {
var second_preimage =
document.getElementById('preimage').value
}
var preimage = voucher['preimage']
var voucherid = voucher['voucherid']
var querykey = voucher['querykey']
var amount = voucher['amount']
var escrow = voucher['escrow']
var lockinghash_according_to_user = voucher['lockinghash']
var templatehash = voucher['templatehash']
if (templatehash == template2hash) {
var driver_privkey = sessionStorage['privkey']
var challenge =
'9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08'
var pubkey = nobleSecp256k1.getPublicKey(
driver_privkey,
true
)
//var lockinghash_based_on_preimage = bitcoinjs.crypto.sha256( buffer.Buffer.from( second_preimage, "hex" ) ).toString( "hex" );
var script = reviseTemplate2(
lockinghash_according_to_user,
challenge,
pubkey
)
var signature = await nobleSecp256k1.sign(
challenge,
driver_privkey
)
var params = []
params.push(signature, second_preimage)
params = JSON.stringify(params)
console.log(signature, script)
var scriptinhex = buffer.Buffer.from(script).toString('hex')
var paramsinhex = buffer.Buffer.from(params).toString('hex')
console.log(scriptinhex, paramsinhex)
var senderscripthash = bitcoinjs.crypto
.sha256(script)
.toString('hex')
var voucherinfofromescrow = await getVoucherInfoFromEscrow(
voucherid
)
voucherinfofromescrow = JSON.parse(voucherinfofromescrow)
console.log('the info returned is', voucherinfofromescrow)
var escrowscripthash = voucherinfofromescrow['scripthash']
console.log(
'script hashes, first from the escrow, then from the sender:',
escrowscripthash,
senderscripthash
)
var senderpmthash = bitcoinjs.crypto
.sha256(buffer.Buffer.from(preimage, 'hex'))
.toString('hex')
var escrowpmthash = voucherinfofromescrow['pmthash']
var senderamount = Number(amount)
var escrowamount = Number(voucherinfofromescrow['amount'])
console.log(
'the script hashes match, right?',
senderscripthash == escrowscripthash
)
if (senderscripthash != escrowscripthash) {
return false
}
console.log(
'the payment hashes match, right?',
senderpmthash == escrowpmthash
)
if (senderpmthash != escrowpmthash) {
return false
}
console.log(
'the amounts match, right?',
senderamount == escrowamount
)
if (senderamount != escrowamount) {
return false
}
if (senderscripthash == escrowscripthash) {
var url =
'https://app9.lightningescrow.io/verify-ownership/?script=' +
scriptinhex +
'¶ms=' +
paramsinhex +
'&voucherid=' +
voucherid
//query whether it returns true or false -- if it returns true, you are the voucher owner, yay!
var i_am_the_owner = await proveOwnership(url)
if (i_am_the_owner == 'true') {
i_am_the_owner = true
} else {
i_am_the_owner = false
}
console.log('i am the owner, right?', i_am_the_owner)
if (i_am_the_owner) {
document.getElementById(
'error banner'
).style.display = 'block'
document.getElementById(
'error banner'
).style.backgroundColor = 'green'
document.getElementById('error banner').innerText =
'You own the voucher'
//var invoice = await makeInvoice( preimage );
console.log(
'here is what I will pass to the makeInvoice function:',
lndendpoint,
lndmacaroon,
senderamount,
preimage,
senderpmthash
)
var invoice = await makeInvoice(
lndendpoint,
lndmacaroon,
senderamount,
preimage,
senderpmthash
)
console.log(
'here is the invoice the makeInvoice function gave me:',
invoice
)
var url =
'https://app9.lightningescrow.io/settle-after-proof/?script=' +
scriptinhex +
'¶ms=' +
paramsinhex +
'&voucherid=' +
voucherid +
'&invoice=' +
invoice
console.log('here is the resulting url:', url)
var json = await settleVoucher(url)
var json = JSON.parse(json)
if (json['status'] == 'success') {
document.getElementById(
'error banner'
).style.display = 'block'
document.getElementById(
'error banner'
).style.backgroundColor = 'green'
document.getElementById(
'error banner'
).innerText =
'Well, you are definitely the full owner of the voucher. Now we will try redeeming it. (You may see this message after you already got paid, check your wallet to be sure.)'
}
}
return i_am_the_owner
}
}
}
</script>
<script>
function isHex(string) {
var a = parseInt(string, 16)
return a.toString(16) === string
}
function askLightningEscrowToPayInvoice(invoice) {
var url =
'https://app6.lightningescrow.io/payinvoiceandsettlewithpreimage/?invoice=' +
invoice
// var url = escrow + "/payinvoiceandsettlewithpreimage/?invoice=" + invoice;
var xhttp = new XMLHttpRequest()
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var json = JSON.parse(xhttp.responseText)
if (json['status'] == 'success') {
console.log(
'yay, they paid the voucher! Time to settle now'
)
} else {
document.getElementById(
'error banner'
).style.display = 'block'
document.getElementById(
'error banner'
).style.backgroundColor = 'red'
document.getElementById('error banner').innerText =
'We could not settle the invoice, please try again'
}
}
}
xhttp.open('GET', url, true)
xhttp.send()
}
async function getVoucherInfoFromEscrow(voucherid) {
var info = ''
var url =
'https://app9.lightningescrow.io/queryforvoucher/?voucherid=' +
voucherid
var xhttp = new XMLHttpRequest()
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
info = xhttp.responseText
}
}
xhttp.open('GET', url, true)
xhttp.send()
async function isInfoSetYet(info_i_seek) {
return new Promise(function (resolve, reject) {
if (info_i_seek == '') {
setTimeout(async function () {
var data = await isInfoSetYet(info)
resolve(data)
}, 100)
} else {
resolve(info_i_seek)
}
})
}
async function getTimeoutData() {
var info_i_seek = await isInfoSetYet(info)
return info_i_seek
}
var returnable = await getTimeoutData()
return returnable
}
async function proveOwnership(url) {
var info = ''
var xhttp = new XMLHttpRequest()
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
info = xhttp.responseText
}
}
xhttp.open('GET', url, true)
xhttp.send()
async function isInfoSetYet(info_i_seek) {
return new Promise(function (resolve, reject) {
if (info_i_seek == '') {
setTimeout(async function () {
var data = await isInfoSetYet(info)
resolve(data)
}, 100)
} else {
resolve(info_i_seek)
}
})
}
async function getTimeoutData() {
var info_i_seek = await isInfoSetYet(info)
return info_i_seek
}
var returnable = await getTimeoutData()
return returnable
}
async function checkIfScriptReturnsTrue(script, params) {
var info = ''
var url =
'https://app9.lightningescrow.io/queryforvoucher/?voucherid=' +
voucherid
var xhttp = new XMLHttpRequest()
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
info = xhttp.responseText
}
}
xhttp.open('GET', url, true)
xhttp.send()
async function isInfoSetYet(info_i_seek) {
return new Promise(function (resolve, reject) {
if (info_i_seek == '') {
setTimeout(async function () {
var data = await isInfoSetYet(info)
resolve(data)
}, 100)
} else {
resolve(info_i_seek)
}
})
}
async function getTimeoutData() {
var info_i_seek = await isInfoSetYet(info)
return info_i_seek
}
var returnable = await getTimeoutData()
return returnable
}
async function settleVoucher(url) {
var info = ''
var xhttp = new XMLHttpRequest()
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
info = xhttp.responseText
}
}
xhttp.open('GET', url, true)
xhttp.send()
async function isInfoSetYet(info_i_seek) {
return new Promise(function (resolve, reject) {
if (info_i_seek == '') {
setTimeout(async function () {
var data = await isInfoSetYet(info)
resolve(data)
}, 100)
} else {
resolve(info_i_seek)
}
})
}
async function getTimeoutData() {
var info_i_seek = await isInfoSetYet(info)
return info_i_seek
}
var returnable = await getTimeoutData()
return returnable
}
function settleInvoice(preimage, endpoint, macaroon) {
var url =
'https://app7.lightningescrow.io/settle-lnd-invoice/?endpoint=' +
endpoint +
'&macaroon=' +
macaroon +
'&preimage=' +
preimage
// var url = escrow + "/settle-lnd-invoice/?endpoint=" + endpoint + "&macaroon=" + macaroon + "&preimage=" + preimage;
var xhttp = new XMLHttpRequest()