-
Notifications
You must be signed in to change notification settings - Fork 2
/
rider.html
979 lines (963 loc) · 29.9 KB
/
rider.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
<!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>Request 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"
/>
</head>
<body>
<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://supertestnet.github.io/bitcoin-chess/js/qrcode.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>
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>
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(sessionStorage['selfsubscription'])
}, 1000)
var filter = {
kinds: [20060],
}
var subscription2 = ['REQ', 'get-kind-sixty', filter]
subscription2 = JSON.stringify(subscription2)
sessionStorage['kindsixtysub'] = subscription2
setTimeout(function () {
socket.send(sessionStorage['kindsixtysub'])
}, 1000)
function subscribe(pubkey) {
var filter = {
authors: [pubkey],
}
var subscription = ['REQ', 'my-sub', filter]
subscription = JSON.stringify(subscription)
sessionStorage.subscription = subscription
socket.send(sessionStorage.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 == 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) {
console.log(event[2].content, event[2].id, event[2].pubkey)
}
})
</script>
<script>
function putOfferOnNostr(offer) {
offer = JSON.stringify(offer)
console.log("note: '" + offer + "'")
var now = Math.floor(new Date().getTime() / 1000)
console.log(now)
var newevent = [0, pubKeyMinus2, now, 20060, [], offer]
var message = JSON.stringify(newevent)
console.log("message: '" + message + "'")
var msghash = bitcoinjs.crypto.sha256(message).toString('hex')
console.log(
"your ride id (save this, you'll need it in case of a dispute):",
msghash
)
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: 20060,
tags: [],
content: offer,
sig: sig,
}
var sendable = ['EVENT', fullevent]
sessionStorage.sendable =
JSON.stringify(sendable)
console.log(
'here is what you will send:',
sendable
)
socket.send(JSON.stringify(sendable))
}
})
})
}
function makeNote(note) {
console.log("note: '" + note + "'")
var now = Math.floor(new Date().getTime() / 1000)
console.log(now)
var newevent = [0, pubKeyMinus2, now, 1, [], note]
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: 1,
tags: [],
content: note,
sig: sig,
}
var sendable = ['EVENT', fullevent]
sessionStorage.sendable =
JSON.stringify(sendable)
socket.send(
'["EVENT",' +
JSON.stringify(
JSON.parse(
sessionStorage.sendable
)[1]
) +
']'
)
}
})
})
}
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)
console.log(
'this is what I am sending:',
JSON.stringify(sendable)
)
socket.send(JSON.stringify(sendable))
console.log(
'ok the private message with this id was sent',
msghash
)
}
})
})
}
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 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 type="text/javascript">
var style = document.createElement('style')
var css = document.createTextNode('#mapid {height: 100%;}')
style.appendChild(css)
document.getElementsByTagName('head')[0].appendChild(style)
</script>
<script
src="https://unpkg.com/[email protected]/dist/leaflet.js"
integrity="sha512-GffPMF3RvMeYyc1LWMHtK8EbPv0iNZ8/oTtHPx9/cc2ILxQ+u905qIwdpULaqDkyBKgOaB57QTMg7ztg8Jm2Og=="
crossorigin=""
></script>
<header id="site_header">
<div id="site-branding">
<h1 class="site-title"><a href="rider.html">Bullrun</a></h1>
</div>
<div id="getting-location">
<p>Getting your location...</p>
</div>
</header>
<main id="site_content">
<section id="rider_map">
<div class="map-wrapper">
<div id="mapid"></div>
</div>
</section>
<section id="rider_payment">
<div id="data_loader">
<img src="images/loader.svg" alt="" />
</div>
<div id="ride_instructions">
<h1>Request a Ride</h1>
<h2>Get started</h2>
<p>Click anywhere on the map to select your destination.</p>
</div>
<div id="invoice box" style="display: none" data-lnbc="">
<h2 class="invoice-title">Pay this invoice</h2>
<p id="invoice instructions"></p>
<div class="payment-wrapper">
<div id="invoice qr" class="qr-code"></div>
<div
id="invoice text"
class="invoice-text copy-to-clipboard"
data-lnbc=""
onClick="copyToClipboard(this.innerText)"
></div>
<button id="open_wallet">
<a href=""> Open Wallet</a>
</button>
</div>
</div>
<div id="preimage" style="display: none">
<h2 class="preimage-title">Your Preimage</h2>
<p id="preimage instructions">
Only show this to your driver when your ride is done. He
needs it to collect his payment. If you get within 100
feet of your destination your device will automatically
send it to him.
</p>
<div
id="preimage qr"
style="
width: 100%;
max-width: 300px;
height: 100%;
max-height: 300px;
border: 1px solid black;
border-radius: 10px;
padding: 10px;
"
></div>
<div
id="preimage text"
style="
display: inline-block;
border: 1px solid black;
text-overflow: break;
word-break: break-all;
"
></div>
</div>
</section>
</main>
<footer id="site_footer">
<div id="snackbar"></div>
<p>
<a
href="https://github.com/supertestnet/bullrun"
target="_blank"
rel="noopener noreferrer"
>Bullrun on Github</a
>
</p>
</footer>
<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 redIcon = new L.Icon({
iconUrl:
'https://streetevangelization.com/wp-content/uploads/2019/09/marker-icon-red.png',
shadowUrl:
'https://streetevangelization.com/wp-content/uploads/2019/09/marker-shadow.png',
iconSize: [25, 41],
iconAnchor: [12, 41],
popupAnchor: [1, -34],
shadowSize: [41, 41],
})
var carIcon = new L.Icon({
iconUrl:
'https://upload.wikimedia.org/wikipedia/commons/thumb/8/8a/Blue_old_car.svg/320px-Blue_old_car.svg.png',
shadowUrl: '',
iconSize: [50, 20],
iconAnchor: [6, 20],
popupAnchor: [1, -34],
shadowSize: [41, 41],
})
var from = {}
var to = {}
var driverimg = {}
var olddist = ''
var finalized = false
var offeramt = ''
var lat = 38
var lng = -95
var zm = 16
//var mymap = L.map('mapid').setView([lat, lng], zm)
sessionStorage['initial-position-is-set'] = false
function getDistance(from, to) {
return (from.distanceTo(to).toFixed(0) / 1609.344).toFixed(3)
}
function watchUsersPosition(position) {
if (
sessionStorage['initial-position-is-set'] == 'false' ||
sessionStorage['initial-position-is-set'] == false
) {
lat = position.coords.latitude
lng = position.coords.longitude
zm = 16
mymap = L.map('mapid').setView([lat, lng], zm)
}
sessionStorage['initial-position-is-set'] = true
if (from != {}) {
mymap.removeLayer(from)
}
if (Object.keys(to).length == 0) {
L.tileLayer(
'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
{
attribution:
'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
}
).addTo(mymap)
}
from = L.marker(
[position.coords.latitude, position.coords.longitude],
{ icon: redIcon }
).addTo(mymap)
if (Object.keys(to).length > 0) {
newdist = getDistance(from.getLatLng(), to.getLatLng())
if (newdist != olddist) {
console.log(newdist + ' mi')
olddist = newdist
if (newdist < 0.021) {
navigator.geolocation.clearWatch(id)
alert("you made it, you're there!")
finalizeAll()
}
}
}
document.getElementById('getting-location').style.display =
'none'
document.getElementById('mapid').style.display = 'block'
mymap.on('click', function (e) {
addMarker(e)
})
function addMarkerByDragging(latlng) {
if (finalized == false) {
if (to != {}) {
mymap.removeLayer(to)
}
to = new L.Marker(latlng, {
draggable: true,
icon: redIcon,
})
to.on('dragend', function (event) {
addMarkerByDragging(event.target._latlng)
})
mymap.addLayer(to)
newdist = getDistance(from.getLatLng(), to.getLatLng())
if (newdist != olddist) {
console.log(newdist + ' mi')
olddist = newdist
var dest_is_final = confirm(
'Please click OK if you are sure this is where you want to go'
)
if (dest_is_final) {
console.log('the destination is final')
addFinalMarker(to.getLatLng())
}
}
}
}
function addMarker(e) {
if (finalized == false) {
if (to != {}) {
mymap.removeLayer(to)
}
to = new L.Marker(e.latlng, {
draggable: true,
icon: redIcon,
})
to.on('dragend', function (event) {
addMarkerByDragging(event.target._latlng)
})
mymap.addLayer(to)
newdist = getDistance(from.getLatLng(), to.getLatLng())
if (newdist != olddist) {
console.log(newdist + ' mi')
olddist = newdist
var dest_is_final = confirm(
'Please click ok if you are sure this is where you want to go'
)
if (dest_is_final) {
console.log('the destination is final')
addFinalMarker(to.getLatLng())
}
}
}
}
async function addFinalMarker(latlng) {
finalized = true
if (to != {}) {
mymap.removeLayer(to)
}
to = new L.Marker(latlng, {
draggable: false,
icon: redIcon,
})
mymap.addLayer(to)
dist = getDistance(from.getLatLng(), to.getLatLng())
/*
newdist = getDistance( from.getLatLng(), to.getLatLng() );
if ( newdist != olddist ) {
console.log( newdist + ' mi' );
olddist = newdist;
var dest_is_final = confirm( "Please click ok if you are sure this is where you want to go" );
if ( dest_is_final ) {
console.log( "the destination is final" );
}
}
*/
offeramt = prompt(
"Please enter a number of sats you're willing to pay a driver to take you there (a good estimate is about a dollar a mile and your destination is " +
newdist +
' miles away)'
)
offeramt = Number(offeramt)
if (!offeramt) {
window.location.reload()
return
}
var fakename = prompt(
'Please enter a fake name for your driver to identify you (a fake name is preferred because it will go on the public internet for all to see)'
)
if (!fakename) {
console.log('there was no fake name')
window.location.reload()
return
}
alert('We are broadcasting your offer to nearby drivers.')
var current_timestamp = Number(
Math.floor(Date.now() / 1000)
)
var seconds_to_wait_for_a_driver_to_accept_your_offer = 300
var offer = {}
offer['type'] = 'offer'
offer['from'] = from.getLatLng()
offer['to'] = to.getLatLng()
offer['amount'] = offeramt
offer['name'] = fakename
offer['expires'] =
Number(current_timestamp) +
Number(
seconds_to_wait_for_a_driver_to_accept_your_offer
)
console.log('offer:', JSON.stringify(offer))
//broadcast the user's offer to nostr
putOfferOnNostr(offer)
var offer_was_broadcasted = true
}
}
getLocation()
function showSubsequentPositions(position) {
mymap.removeLayer(from)
from = L.marker(
[position.coords.latitude, position.coords.longitude],
{ icon: redIcon }
).addTo(mymap)
}
</script>
<script>
var escrow = 'https://app7.lightningescrow.io'
function createQR(content) {
var dataUriPngImage = document.createElement('img'),
s = QRCode.generatePNG(content, {
ecclevel: 'M',
format: 'html',
fillcolor: '#FFFFFF',
textcolor: '#373737',
margin: 4,
modulesize: 8,
})
dataUriPngImage.src = s
dataUriPngImage.id = 'qr_code'
return dataUriPngImage
}
function loopChecker(
pmthash,
preimage,
amount,
voucherid,
querykey,
templatehash,
lockinghash,
drivercommskey,
second_preimage
) {
var url =
'https://app6.lightningescrow.io/getinvoicestatusv2/?pmthash=' +
pmthash
var xhttp = new XMLHttpRequest()
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
if (xhttp.responseText == 'ACCEPTED') {
console.log(xhttp.responseText)
var voucher = {}
voucher['preimage'] = preimage
voucher['lockinghash'] = lockinghash
voucher['voucherid'] = voucherid
voucher['querykey'] = querykey
voucher['amount'] = amount
voucher['escrow'] = escrow
voucher['templatehash'] = templatehash
voucher = JSON.stringify(voucher)
voucherhex =
buffer.Buffer.from(voucher).toString('hex')
console.log('here is the voucher:', voucher)
console.log(
'here is the voucher in hex:',
voucherhex
)
//send the voucherhex to the driver in a nostr dm
var message = {}
message['type'] = 'agree'
message['voucher'] = voucherhex
message = JSON.stringify(message)
sessionStorage['driver'] = drivercommskey
makePrivateNote(message, drivercommskey)
alert(
'Your driver is on the way. You can track them on the map. Please show them the qr code under the map when your ride is over, your driver will use it to collect your money.'
)
document
.getElementById('preimage qr')
.append(createQR(second_preimage))
document.getElementById('preimage text').innerText =
second_preimage
document.getElementById( "invoice qr" ).firstChild.src = document.getElementById( "preimage qr" ).firstChild.src
document.getElementById( "invoice text" ).innerHTML = document.getElementById( "preimage text" ).innerHTML
document.getElementsByClassName( "invoice-title" )[ 0 ].innerHTML = document.getElementsByClassName( "preimage-title" )[ 0 ].innerHTML
document.getElementById( "invoice instructions" ).innerHTML = document.getElementById( "preimage instructions" ).innerHTML
document.getElementById( "open_wallet" ).style.display = 'none'
// document.getElementById(
// 'preimage box'
// ).style.display = 'block'
// document.getElementById('preimage').style.display =
// 'block'
sessionStorage['second_preimage'] = second_preimage
//remember to show the driver's location on the map
//let the rider share their live location with a friend. Girl riders feel more comfortable if someone knows they are with a stranger and where they are
} else if (xhttp.responseText != 'SETTLED') {
console.log(xhttp.responseText)
var voucher = {}
voucher['preimage'] = preimage
voucher['lockinghash'] = lockinghash
voucher['voucherid'] = voucherid
voucher['querykey'] = querykey
voucher['amount'] = amount
voucher['escrow'] = escrow
voucher['templatehash'] = templatehash
voucher = JSON.stringify(voucher)
voucherhex =
buffer.Buffer.from(voucher).toString('hex')
console.log(
'do not show the voucher yet...but here it is:',
voucher
)
console.log(
'and here is the voucher in hex:',
voucherhex
)
setTimeout(function () {
loopChecker(
pmthash,
preimage,
amount,
voucherid,
querykey,
templatehash,
lockinghash,
drivercommskey,
second_preimage
)
}, 5000)
} else {
console.log("Well, you don't need me anymore")
}
}
}
xhttp.open('GET', url, true)
xhttp.send()
}
function makeVoucher(
hash,
drivercommskey,
driverpubkey,
second_preimage
) {
var lockinghash = hash
var challenge =
'9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08'
var preimage = bitcoinjs.ECPair.makeRandom().__D.toString('hex')
var pmthash = bitcoinjs.crypto
.sha256(buffer.Buffer.from(preimage, 'hex'))
.toString('hex')
var template = `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 templatehash = bitcoinjs.crypto
.sha256(template)
.toString('hex')
var script =
`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 +
`", "` +
driverpubkey +
`" );}}`
var scripthash = bitcoinjs.crypto.sha256(script).toString('hex')
console.log('here is the script:', script)
console.log('here is the script hash:', scripthash)
var amount = offeramt
var querykey = bitcoinjs.ECPair.makeRandom()
var queryprivkey = querykey.privateKey.toString('hex')
var querypubkey = querykey.publicKey.toString('hex')
var url =
'https://app9.lightningescrow.io/gethodlinvoice/?pmthash=' +
pmthash +
'&scripthash=' +
scripthash +
'&amount=' +
amount.toString() +
'&querykey=' +
querypubkey
var xhttp = new XMLHttpRequest()
xhttp.onreadystatechange = function () {
document.getElementById('ride_instructions').style.display =
'none'
document.getElementById('data_loader').style.display =
'inline-block'
if (this.readyState == 4 && this.status == 200) {
var prepjson = xhttp.responseText
prepjson = prepjson.substring(
0,
prepjson.indexOf('}') + 1
)
console.log(prepjson)
var json = JSON.parse(prepjson)
console.log([1])
var invoice = json['invoice']
var voucherid = json['voucher_id']
console.log('invoice:', invoice)
console.log('voucherid:', voucherid)
document
.getElementById('invoice qr')
.append(createQR(invoice))
document.getElementById('invoice text').innerText =
invoice
document
.getElementById('invoice box')
.setAttribute('data-lnbc', invoice)
document
.getElementById('invoice text')
.setAttribute('data-lnbc', invoice)
document
.getElementById('open_wallet')
.firstElementChild.setAttribute(
'href',
'lightning:' + invoice
)
document.getElementById('data_loader').style.display =
'none'
document.getElementById('invoice box').style.display =
'block'
console.log('pay this invoice:', invoice)
console.log(
'voucherid right before it gets passed to loopchecker:',
voucherid
)
loopChecker(
pmthash,
preimage,
amount,
voucherid,
queryprivkey,
templatehash,
lockinghash,
drivercommskey,
second_preimage
)
}
}
xhttp.open('GET', url, true)
xhttp.send()
}
</script>
<script>
function decideMessageTypeAndNextSteps(message, driver) {
message = JSON.parse(message)
var type = message['type']
if (type == 'acceptance') {
var name = message['name']
var vehicle = message['vehicle']
var coordinates = message['coordinates']
var coordinatesobj = L.marker(coordinates)
var driver_dist = getDistance(
from.getLatLng(),
coordinatesobj.getLatLng()
)
var driver_was_found = confirm(
'Click ok if you want ' +
name +
' to pick you up in their ' +
vehicle +
', they are currently ' +
driver_dist +
' miles away'
)
if (!driver_was_found) {
return
}
//send a message to nostr marking the offer message fulfilled
var offer_was_marked_fulfilled = true
var recipient = message['pubkey']
//create a random preimage and hash it, then create a lightning voucher locked by that hash -- and prepare to show the second preimage to the driver in the form of a qr code
var second_preimage =
bitcoinjs.ECPair.makeRandom().privateKey.toString('hex')
console.log(
'here is the preimage the driver will eventually get assuming no dispute:',
second_preimage
)
var hash = bitcoinjs.crypto
.sha256(buffer.Buffer.from(second_preimage, 'hex'))
.toString('hex')
makeVoucher(hash, driver, recipient, second_preimage)
}
if (type == 'location') {
console.log(driverlocation)
var driverlocation = message['location']
if (driverimg != {}) {
mymap.removeLayer(driverimg)
}
driverimg = new L.Marker(driverlocation, { icon: carIcon })
mymap.addLayer(driverimg)
}
}
</script>
<script>
function finalizeAll() {
var message = {}
message['type'] = 'finalize'
message['preimage'] = sessionStorage['second_preimage']
message = JSON.stringify(message)
var drivercommskey = sessionStorage['driver']
makePrivateNote(message, drivercommskey)
console.log('congratulations, you reached your destination')
}
</script>
<script>
function showToast(string) {
var x = document.getElementById('snackbar')
x.className = 'show'
x.innerText = string
setTimeout(function () {
x.className = x.className.replace('show', '')
}, 3000)
}
</script>
<script>
function copyToClipboard(value) {
navigator.clipboard.writeText(value)
showToast('Copied to clipboard')
}
</script>
</body>
</html>