-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.html
2540 lines (2316 loc) · 499 KB
/
index.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
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>JavaScript Bitcoin BrainWallet Generator and Construct Transaction and Offline Sign Transaction / Ethereum BrainWallet Generator(比特币脑钱包生成器,以太坊脑钱包生成器) - JS Demonstration of Bitcoin and Ethereum Brain Password, Private Key, Public Key, and Address Generation Steps and Relationships(JS演示比特币和以太坊脑口令、私钥、公钥及地址生成步骤及相互关系) - Construct Transaction and Sign Transaction构建交易并签交易名</title>
<meta name="keywords" content="javascript, bitcoin, brainwallet, cold wallet, offline wallet, construct transaction, offline sign, ethereum">
<style type="text/css">
#ethereum{display:none}
.menu, .preface, .brain, .priKey, .pubKey, .address, .VerifySignature, .TX {border-style:solid; border-width:5px; border-color:428bca; padding:0px 3px 3px 3px}
.menu, .h1 {background:#428bca; color:white; font-size:20px; font-weight:bold}
.h2 {font-weight:bold; font-size:13px; display:float}
button {cursor:pointer; overflow-wrap:break-word; word-break:break-all}
button:hOver{background:#428BCA; color:white}
textarea {margin-top:1px; font-size:13px; width:100%; word-break:break-all}
p {margin:0px; font-size:13px; display:inline; overflow-wrap:break-word; word-break:break-all}
.buttonh1 {font-size:15px; font-weight:bold}
select {width:100%}
.open-before{height:50px; overflow:hidden}
.open-after{height:auto; overflow:auto}
.hidden{display:block; width:100%; margin:0 45%; display:none}
.show{display:block; width:100%; margin:0 45%; display:block}
</style>
<script type="text/javascript">
/* 时间戳转换为时间 */
/*function timestampToTime(timestamp) {
timestamp = timestamp ? timestamp : null;
let date = new Date(timestamp);//时间戳为10位需*1000,时间戳为13位的话不需乘1000
let Y = date.getFullYear() + '-';
let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
let h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
let m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
return Y + M + D + h + m + s;
}*/
var url = "https://api.coincap.io/v2/rates";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.setRequestHeader("Authorization", "Bearer c017c408-a39f-4f01-ab98-485b1403c0e4");
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
var result = myObj["data"].find(function(item){return item.id === "bitcoin"});
var btcUsd = Math.round(result["rateUsd"] * 100) / 100;
result = myObj["data"].find(function(item){return item.id === "chinese-yuan-renminbi"});
var btcCny = Math.round(1 / result["rateUsd"] * btcUsd * 100) / 100; //保留两位小数
document.getElementById('priceUsd').innerHTML = "Realtime Price(实时价格): <font style='font-weight:bold; color:red'>" + btcUsd + "$, " + btcCny + "¥</font>";
}
};
//textarea行高自适应内容
function ResizeTextarea(textArea,minRows,maxRows){
if (textArea.scrollTop == 0) textArea.scrollTop=1;
while (textArea.scrollTop == 0){
if (textArea.rows > minRows)
textArea.rows--;
else
break;
textArea.scrollTop = 1;
if (textArea.rows < maxRows)
textArea.style.overflowY = "hidden";
if (textArea.scrollTop > 0){
textArea.rows++;
break;
}
}
while(textArea.scrollTop > 0){
if (textArea.rows < maxRows){
textArea.rows++;
if (textArea.scrollTop == 0) textArea.scrollTop=1;
}
else{
textArea.style.overflowY = "auto";
break;
}
}
}
function openContent(contentID, openbtnID, closebtnID) {
document.getElementById(contentID).className = 'open-after';
document.getElementById(openbtnID).className= 'hidden';
document.getElementById(closebtnID).className= 'show';
}
function closeContent(contentID, openbtnID, closebtnID) {
document.getElementById(contentID).className = 'open-before';
document.getElementById(closebtnID).className= 'hidden';
document.getElementById(openbtnID).className= 'show';
}
//判读是否是十六进制
function isHex(str) {
return !/[^0123456789abcdef]+/i.test(str);
}
//生成助记词
function toMnemonic(entropy,mnemonicNum) {
var o = {};
var seed = "";
var mnemonic_en = [];
var mnemonic_cn = [];
o.seed = seed;
o.mnemonic_en = mnemonic_en;
o.mnemonic_cn = mnemonic_cn;
if (entropy.length < 32) {
return o;
}
else if (!isHex(entropy.substr(0,32))) {
return o;
}
var wordlist_en = "abandon ability able about above absent absorb abstract absurd abuse access accident account accuse achieve acid acoustic acquire across act action actor actress actual adapt add addict address adjust admit adult advance advice aerobic affair afford afraid again age agent agree ahead aim air airport aisle alarm album alcohol alert alien all alley allow almost alone alpha already also alter always amateur amazing among amount amused analyst anchor ancient anger angle angry animal ankle announce annual another answer antenna antique anxiety any apart apology appear apple approve april arch arctic area arena argue arm armed armor army around arrange arrest arrive arrow art artefact artist artwork ask aspect assault asset assist assume asthma athlete atom attack attend attitude attract auction audit august aunt author auto autumn average avocado avoid awake aware away awesome awful awkward axis baby bachelor bacon badge bag balance balcony ball bamboo banana banner bar barely bargain barrel base basic basket battle beach bean beauty because become beef before begin behave behind believe below belt bench benefit best betray better between beyond bicycle bid bike bind biology bird birth bitter black blade blame blanket blast bleak bless blind blood blossom blouse blue blur blush board boat body boil bomb bone bonus book boost border boring borrow boss bottom bounce box boy bracket brain brand brass brave bread breeze brick bridge brief bright bring brisk broccoli broken bronze broom brother brown brush bubble buddy budget buffalo build bulb bulk bullet bundle bunker burden burger burst bus business busy butter buyer buzz cabbage cabin cable cactus cage cake call calm camera camp can canal cancel candy cannon canoe canvas canyon capable capital captain car carbon card cargo carpet carry cart case cash casino castle casual cat catalog catch category cattle caught cause caution cave ceiling celery cement census century cereal certain chair chalk champion change chaos chapter charge chase chat cheap check cheese chef cherry chest chicken chief child chimney choice choose chronic chuckle chunk churn cigar cinnamon circle citizen city civil claim clap clarify claw clay clean clerk clever click client cliff climb clinic clip clock clog close cloth cloud clown club clump cluster clutch coach coast coconut code coffee coil coin collect color column combine come comfort comic common company concert conduct confirm congress connect consider control convince cook cool copper copy coral core corn correct cost cotton couch country couple course cousin cover coyote crack cradle craft cram crane crash crater crawl crazy cream credit creek crew cricket crime crisp critic crop cross crouch crowd crucial cruel cruise crumble crunch crush cry crystal cube culture cup cupboard curious current curtain curve cushion custom cute cycle dad damage damp dance danger daring dash daughter dawn day deal debate debris decade december decide decline decorate decrease deer defense define defy degree delay deliver demand demise denial dentist deny depart depend deposit depth deputy derive describe desert design desk despair destroy detail detect develop device devote diagram dial diamond diary dice diesel diet differ digital dignity dilemma dinner dinosaur direct dirt disagree discover disease dish dismiss disorder display distance divert divide divorce dizzy doctor document dog doll dolphin domain donate donkey donor door dose double dove draft dragon drama drastic draw dream dress drift drill drink drip drive drop drum dry duck dumb dune during dust dutch duty dwarf dynamic eager eagle early earn earth easily east easy echo ecology economy edge edit educate effort egg eight either elbow elder electric elegant element elephant elevator elite else embark embody embrace emerge emotion employ empower empty enable enact end endless endorse enemy energy enforce engage engine enhance enjoy enlist enough enrich enroll ensure enter entire entry envelope episode equal equip era erase erode erosion error erupt escape essay essence estate eternal ethics evidence evil evoke evolve exact example excess exchange excite exclude excuse execute exercise exhaust exhibit exile exist exit exotic expand expect expire explain expose express extend extra eye eyebrow fabric face faculty fade faint faith fall false fame family famous fan fancy fantasy farm fashion fat fatal father fatigue fault favorite feature february federal fee feed feel female fence festival fetch fever few fiber fiction field figure file film filter final find fine finger finish fire firm first fiscal fish fit fitness fix flag flame flash flat flavor flee flight flip float flock floor flower fluid flush fly foam focus fog foil fold follow food foot force forest forget fork fortune forum forward fossil foster found fox fragile frame frequent fresh friend fringe frog front frost frown frozen fruit fuel fun funny furnace fury future gadget gain galaxy gallery game gap garage garbage garden garlic garment gas gasp gate gather gauge gaze general genius genre gentle genuine gesture ghost giant gift giggle ginger giraffe girl give glad glance glare glass glide glimpse globe gloom glory glove glow glue goat goddess gold good goose gorilla gospel gossip govern gown grab grace grain grant grape grass gravity great green grid grief grit grocery group grow grunt guard guess guide guilt guitar gun gym habit hair half hammer hamster hand happy harbor hard harsh harvest hat have hawk hazard head health heart heavy hedgehog height hello helmet help hen hero hidden high hill hint hip hire history hobby hockey hold hole holiday hollow home honey hood hope horn horror horse hospital host hotel hour hover hub huge human humble humor hundred hungry hunt hurdle hurry hurt husband hybrid ice icon idea identify idle ignore ill illegal illness image imitate immense immune impact impose improve impulse inch include income increase index indicate indoor industry infant inflict inform inhale inherit initial inject injury inmate inner innocent input inquiry insane insect inside inspire install intact interest into invest invite involve iron island isolate issue item ivory jacket jaguar jar jazz jealous jeans jelly jewel job join joke journey joy judge juice jump jungle junior junk just kangaroo keen keep ketchup key kick kid kidney kind kingdom kiss kit kitchen kite kitten kiwi knee knife knock know lab label labor ladder lady lake lamp language laptop large later latin laugh laundry lava law lawn lawsuit layer lazy leader leaf learn leave lecture left leg legal legend leisure lemon lend length lens leopard lesson letter level liar liberty library license life lift light like limb limit link lion liquid list little live lizard load loan lobster local lock logic lonely long loop lottery loud lounge love loyal lucky luggage lumber lunar lunch luxury lyrics machine mad magic magnet maid mail main major make mammal man manage mandate mango mansion manual maple marble march margin marine market marriage mask mass master match material math matrix matter maximum maze meadow mean measure meat mechanic medal media melody melt member memory mention menu mercy merge merit merry mesh message metal method middle midnight milk million mimic mind minimum minor minute miracle mirror misery miss mistake mix mixed mixture mobile model modify mom moment monitor monkey monster month moon moral more morning mosquito mother motion motor mountain mouse move movie much muffin mule multiply muscle museum mushroom music must mutual myself mystery myth naive name napkin narrow nasty nation nature near neck need negative neglect neither nephew nerve nest net network neutral never news next nice night noble noise nominee noodle normal north nose notable note nothing notice novel now nuclear number nurse nut oak obey object oblige obscure observe obtain obvious occur ocean october odor off offer office often oil okay old olive olympic omit once one onion online only open opera opinion oppose option orange orbit orchard order ordinary organ orient original orphan ostrich other outdoor outer output outside oval oven over own owner oxygen oyster ozone pact paddle page pair palace palm panda panel panic panther paper parade parent park parrot party pass patch path patient patrol pattern pause pave payment peace peanut pear peasant pelican pen penalty pencil people pepper perfect permit person pet phone photo phrase physical piano picnic picture piece pig pigeon pill pilot pink pioneer pipe pistol pitch pizza place planet plastic plate play please pledge pluck plug plunge poem poet point polar pole police pond pony pool popular portion position possible post potato pottery poverty powder power practice praise predict prefer prepare present pretty prevent price pride primary print priority prison private prize problem process produce profit program project promote proof property prosper protect proud provide public pudding pull pulp pulse pumpkin punch pupil puppy purchase purity purpose purse push put puzzle pyramid quality quantum quarter question quick quit quiz quote rabbit raccoon race rack radar radio rail rain raise rally ramp ranch random range rapid rare rate rather raven raw razor ready real reason rebel rebuild recall receive recipe record recycle reduce reflect reform refuse region regret regular reject relax release relief rely remain remember remind remove render renew rent reopen repair repeat replace report require rescue resemble resist resource response result retire retreat return reunion reveal review reward rhythm rib ribbon rice rich ride ridge rifle right rigid ring riot ripple risk ritual rival river road roast robot robust rocket romance roof rookie room rose rotate rough round route royal rubber rude rug rule run runway rural sad saddle sadness safe sail salad salmon salon salt salute same sample sand satisfy satoshi sauce sausage save say scale scan scare scatter scene scheme school science scissors scorpion scout scrap screen script scrub sea search season seat second secret section security seed seek segment select sell seminar senior sense sentence series service session settle setup seven shadow shaft shallow share shed shell sheriff shield shift shine ship shiver shock shoe shoot shop short shoulder shove shrimp shrug shuffle shy sibling sick side siege sight sign silent silk silly silver similar simple since sing siren sister situate six size skate sketch ski skill skin skirt skull slab slam sleep slender slice slide slight slim slogan slot slow slush small smart smile smoke smooth snack snake snap sniff snow soap soccer social sock soda soft solar soldier solid solution solve someone song soon sorry sort soul sound soup source south space spare spatial spawn speak special speed spell spend sphere spice spider spike spin spirit split spoil sponsor spoon sport spot spray spread spring spy square squeeze squirrel stable stadium staff stage stairs stamp stand start state stay steak steel stem step stereo stick still sting stock stomach stone stool story stove strategy street strike strong struggle student stuff stumble style subject submit subway success such sudden suffer sugar suggest suit summer sun sunny sunset super supply supreme sure surface surge surprise surround survey suspect sustain swallow swamp swap swarm swear sweet swift swim swing switch sword symbol symptom syrup system table tackle tag tail talent talk tank tape target task taste tattoo taxi teach team tell ten tenant tennis tent term test text thank that theme then theory there they thing this thought three thrive throw thumb thunder ticket tide tiger tilt timber time tiny tip tired tissue title toast tobacco today toddler toe together toilet token tomato tomorrow tone tongue tonight tool tooth top topic topple torch tornado tortoise toss total tourist toward tower town toy track trade traffic tragic train transfer trap trash travel tray treat tree trend trial tribe trick trigger trim trip trophy trouble truck true truly trumpet trust truth try tube tuition tumble tuna tunnel turkey turn turtle twelve twenty twice twin twist two type typical ugly umbrella unable unaware uncle uncover under undo unfair unfold unhappy uniform unique unit universe unknown unlock until unusual unveil update upgrade uphold upon upper upset urban urge usage use used useful useless usual utility vacant vacuum vague valid valley valve van vanish vapor various vast vault vehicle velvet vendor venture venue verb verify version very vessel veteran viable vibrant vicious victory video view village vintage violin virtual virus visa visit visual vital vivid vocal voice void volcano volume vote voyage wage wagon wait walk wall walnut want warfare warm warrior wash wasp waste water wave way wealth weapon wear weasel weather web wedding weekend weird welcome west wet whale what wheat wheel when where whip whisper wide width wife wild will win window wine wing wink winner winter wire wisdom wise wish witness wolf woman wonder wood wool word work world worry worth wrap wreck wrestle wrist write wrong yard year yellow you young youth zebra zero zone zoo";
var wordlist_cn = "的 一 是 在 不 了 有 和 人 这 中 大 为 上 个 国 我 以 要 他 时 来 用 们 生 到 作 地 于 出 就 分 对 成 会 可 主 发 年 动 同 工 也 能 下 过 子 说 产 种 面 而 方 后 多 定 行 学 法 所 民 得 经 十 三 之 进 着 等 部 度 家 电 力 里 如 水 化 高 自 二 理 起 小 物 现 实 加 量 都 两 体 制 机 当 使 点 从 业 本 去 把 性 好 应 开 它 合 还 因 由 其 些 然 前 外 天 政 四 日 那 社 义 事 平 形 相 全 表 间 样 与 关 各 重 新 线 内 数 正 心 反 你 明 看 原 又 么 利 比 或 但 质 气 第 向 道 命 此 变 条 只 没 结 解 问 意 建 月 公 无 系 军 很 情 者 最 立 代 想 已 通 并 提 直 题 党 程 展 五 果 料 象 员 革 位 入 常 文 总 次 品 式 活 设 及 管 特 件 长 求 老 头 基 资 边 流 路 级 少 图 山 统 接 知 较 将 组 见 计 别 她 手 角 期 根 论 运 农 指 几 九 区 强 放 决 西 被 干 做 必 战 先 回 则 任 取 据 处 队 南 给 色 光 门 即 保 治 北 造 百 规 热 领 七 海 口 东 导 器 压 志 世 金 增 争 济 阶 油 思 术 极 交 受 联 什 认 六 共 权 收 证 改 清 美 再 采 转 更 单 风 切 打 白 教 速 花 带 安 场 身 车 例 真 务 具 万 每 目 至 达 走 积 示 议 声 报 斗 完 类 八 离 华 名 确 才 科 张 信 马 节 话 米 整 空 元 况 今 集 温 传 土 许 步 群 广 石 记 需 段 研 界 拉 林 律 叫 且 究 观 越 织 装 影 算 低 持 音 众 书 布 复 容 儿 须 际 商 非 验 连 断 深 难 近 矿 千 周 委 素 技 备 半 办 青 省 列 习 响 约 支 般 史 感 劳 便 团 往 酸 历 市 克 何 除 消 构 府 称 太 准 精 值 号 率 族 维 划 选 标 写 存 候 毛 亲 快 效 斯 院 查 江 型 眼 王 按 格 养 易 置 派 层 片 始 却 专 状 育 厂 京 识 适 属 圆 包 火 住 调 满 县 局 照 参 红 细 引 听 该 铁 价 严 首 底 液 官 德 随 病 苏 失 尔 死 讲 配 女 黄 推 显 谈 罪 神 艺 呢 席 含 企 望 密 批 营 项 防 举 球 英 氧 势 告 李 台 落 木 帮 轮 破 亚 师 围 注 远 字 材 排 供 河 态 封 另 施 减 树 溶 怎 止 案 言 士 均 武 固 叶 鱼 波 视 仅 费 紧 爱 左 章 早 朝 害 续 轻 服 试 食 充 兵 源 判 护 司 足 某 练 差 致 板 田 降 黑 犯 负 击 范 继 兴 似 余 坚 曲 输 修 故 城 夫 够 送 笔 船 占 右 财 吃 富 春 职 觉 汉 画 功 巴 跟 虽 杂 飞 检 吸 助 升 阳 互 初 创 抗 考 投 坏 策 古 径 换 未 跑 留 钢 曾 端 责 站 简 述 钱 副 尽 帝 射 草 冲 承 独 令 限 阿 宣 环 双 请 超 微 让 控 州 良 轴 找 否 纪 益 依 优 顶 础 载 倒 房 突 坐 粉 敌 略 客 袁 冷 胜 绝 析 块 剂 测 丝 协 诉 念 陈 仍 罗 盐 友 洋 错 苦 夜 刑 移 频 逐 靠 混 母 短 皮 终 聚 汽 村 云 哪 既 距 卫 停 烈 央 察 烧 迅 境 若 印 洲 刻 括 激 孔 搞 甚 室 待 核 校 散 侵 吧 甲 游 久 菜 味 旧 模 湖 货 损 预 阻 毫 普 稳 乙 妈 植 息 扩 银 语 挥 酒 守 拿 序 纸 医 缺 雨 吗 针 刘 啊 急 唱 误 训 愿 审 附 获 茶 鲜 粮 斤 孩 脱 硫 肥 善 龙 演 父 渐 血 欢 械 掌 歌 沙 刚 攻 谓 盾 讨 晚 粒 乱 燃 矛 乎 杀 药 宁 鲁 贵 钟 煤 读 班 伯 香 介 迫 句 丰 培 握 兰 担 弦 蛋 沉 假 穿 执 答 乐 谁 顺 烟 缩 征 脸 喜 松 脚 困 异 免 背 星 福 买 染 井 概 慢 怕 磁 倍 祖 皇 促 静 补 评 翻 肉 践 尼 衣 宽 扬 棉 希 伤 操 垂 秋 宜 氢 套 督 振 架 亮 末 宪 庆 编 牛 触 映 雷 销 诗 座 居 抓 裂 胞 呼 娘 景 威 绿 晶 厚 盟 衡 鸡 孙 延 危 胶 屋 乡 临 陆 顾 掉 呀 灯 岁 措 束 耐 剧 玉 赵 跳 哥 季 课 凯 胡 额 款 绍 卷 齐 伟 蒸 殖 永 宗 苗 川 炉 岩 弱 零 杨 奏 沿 露 杆 探 滑 镇 饭 浓 航 怀 赶 库 夺 伊 灵 税 途 灭 赛 归 召 鼓 播 盘 裁 险 康 唯 录 菌 纯 借 糖 盖 横 符 私 努 堂 域 枪 润 幅 哈 竟 熟 虫 泽 脑 壤 碳 欧 遍 侧 寨 敢 彻 虑 斜 薄 庭 纳 弹 饲 伸 折 麦 湿 暗 荷 瓦 塞 床 筑 恶 户 访 塔 奇 透 梁 刀 旋 迹 卡 氯 遇 份 毒 泥 退 洗 摆 灰 彩 卖 耗 夏 择 忙 铜 献 硬 予 繁 圈 雪 函 亦 抽 篇 阵 阴 丁 尺 追 堆 雄 迎 泛 爸 楼 避 谋 吨 野 猪 旗 累 偏 典 馆 索 秦 脂 潮 爷 豆 忽 托 惊 塑 遗 愈 朱 替 纤 粗 倾 尚 痛 楚 谢 奋 购 磨 君 池 旁 碎 骨 监 捕 弟 暴 割 贯 殊 释 词 亡 壁 顿 宝 午 尘 闻 揭 炮 残 冬 桥 妇 警 综 招 吴 付 浮 遭 徐 您 摇 谷 赞 箱 隔 订 男 吹 园 纷 唐 败 宋 玻 巨 耕 坦 荣 闭 湾 键 凡 驻 锅 救 恩 剥 凝 碱 齿 截 炼 麻 纺 禁 废 盛 版 缓 净 睛 昌 婚 涉 筒 嘴 插 岸 朗 庄 街 藏 姑 贸 腐 奴 啦 惯 乘 伙 恢 匀 纱 扎 辩 耳 彪 臣 亿 璃 抵 脉 秀 萨 俄 网 舞 店 喷 纵 寸 汗 挂 洪 贺 闪 柬 爆 烯 津 稻 墙 软 勇 像 滚 厘 蒙 芳 肯 坡 柱 荡 腿 仪 旅 尾 轧 冰 贡 登 黎 削 钻 勒 逃 障 氨 郭 峰 币 港 伏 轨 亩 毕 擦 莫 刺 浪 秘 援 株 健 售 股 岛 甘 泡 睡 童 铸 汤 阀 休 汇 舍 牧 绕 炸 哲 磷 绩 朋 淡 尖 启 陷 柴 呈 徒 颜 泪 稍 忘 泵 蓝 拖 洞 授 镜 辛 壮 锋 贫 虚 弯 摩 泰 幼 廷 尊 窗 纲 弄 隶 疑 氏 宫 姐 震 瑞 怪 尤 琴 循 描 膜 违 夹 腰 缘 珠 穷 森 枝 竹 沟 催 绳 忆 邦 剩 幸 浆 栏 拥 牙 贮 礼 滤 钠 纹 罢 拍 咱 喊 袖 埃 勤 罚 焦 潜 伍 墨 欲 缝 姓 刊 饱 仿 奖 铝 鬼 丽 跨 默 挖 链 扫 喝 袋 炭 污 幕 诸 弧 励 梅 奶 洁 灾 舟 鉴 苯 讼 抱 毁 懂 寒 智 埔 寄 届 跃 渡 挑 丹 艰 贝 碰 拔 爹 戴 码 梦 芽 熔 赤 渔 哭 敬 颗 奔 铅 仲 虎 稀 妹 乏 珍 申 桌 遵 允 隆 螺 仓 魏 锐 晓 氮 兼 隐 碍 赫 拨 忠 肃 缸 牵 抢 博 巧 壳 兄 杜 讯 诚 碧 祥 柯 页 巡 矩 悲 灌 龄 伦 票 寻 桂 铺 圣 恐 恰 郑 趣 抬 荒 腾 贴 柔 滴 猛 阔 辆 妻 填 撤 储 签 闹 扰 紫 砂 递 戏 吊 陶 伐 喂 疗 瓶 婆 抚 臂 摸 忍 虾 蜡 邻 胸 巩 挤 偶 弃 槽 劲 乳 邓 吉 仁 烂 砖 租 乌 舰 伴 瓜 浅 丙 暂 燥 橡 柳 迷 暖 牌 秧 胆 详 簧 踏 瓷 谱 呆 宾 糊 洛 辉 愤 竞 隙 怒 粘 乃 绪 肩 籍 敏 涂 熙 皆 侦 悬 掘 享 纠 醒 狂 锁 淀 恨 牲 霸 爬 赏 逆 玩 陵 祝 秒 浙 貌 役 彼 悉 鸭 趋 凤 晨 畜 辈 秩 卵 署 梯 炎 滩 棋 驱 筛 峡 冒 啥 寿 译 浸 泉 帽 迟 硅 疆 贷 漏 稿 冠 嫩 胁 芯 牢 叛 蚀 奥 鸣 岭 羊 凭 串 塘 绘 酵 融 盆 锡 庙 筹 冻 辅 摄 袭 筋 拒 僚 旱 钾 鸟 漆 沈 眉 疏 添 棒 穗 硝 韩 逼 扭 侨 凉 挺 碗 栽 炒 杯 患 馏 劝 豪 辽 勃 鸿 旦 吏 拜 狗 埋 辊 掩 饮 搬 骂 辞 勾 扣 估 蒋 绒 雾 丈 朵 姆 拟 宇 辑 陕 雕 偿 蓄 崇 剪 倡 厅 咬 驶 薯 刷 斥 番 赋 奉 佛 浇 漫 曼 扇 钙 桃 扶 仔 返 俗 亏 腔 鞋 棱 覆 框 悄 叔 撞 骗 勘 旺 沸 孤 吐 孟 渠 屈 疾 妙 惜 仰 狠 胀 谐 抛 霉 桑 岗 嘛 衰 盗 渗 脏 赖 涌 甜 曹 阅 肌 哩 厉 烃 纬 毅 昨 伪 症 煮 叹 钉 搭 茎 笼 酷 偷 弓 锥 恒 杰 坑 鼻 翼 纶 叙 狱 逮 罐 络 棚 抑 膨 蔬 寺 骤 穆 冶 枯 册 尸 凸 绅 坯 牺 焰 轰 欣 晋 瘦 御 锭 锦 丧 旬 锻 垄 搜 扑 邀 亭 酯 迈 舒 脆 酶 闲 忧 酚 顽 羽 涨 卸 仗 陪 辟 惩 杭 姚 肚 捉 飘 漂 昆 欺 吾 郎 烷 汁 呵 饰 萧 雅 邮 迁 燕 撒 姻 赴 宴 烦 债 帐 斑 铃 旨 醇 董 饼 雏 姿 拌 傅 腹 妥 揉 贤 拆 歪 葡 胺 丢 浩 徽 昂 垫 挡 览 贪 慰 缴 汪 慌 冯 诺 姜 谊 凶 劣 诬 耀 昏 躺 盈 骑 乔 溪 丛 卢 抹 闷 咨 刮 驾 缆 悟 摘 铒 掷 颇 幻 柄 惠 惨 佳 仇 腊 窝 涤 剑 瞧 堡 泼 葱 罩 霍 捞 胎 苍 滨 俩 捅 湘 砍 霞 邵 萄 疯 淮 遂 熊 粪 烘 宿 档 戈 驳 嫂 裕 徙 箭 捐 肠 撑 晒 辨 殿 莲 摊 搅 酱 屏 疫 哀 蔡 堵 沫 皱 畅 叠 阁 莱 敲 辖 钩 痕 坝 巷 饿 祸 丘 玄 溜 曰 逻 彭 尝 卿 妨 艇 吞 韦 怨 矮 歇";
wordlist_en = wordlist_en.split(" ");
wordlist_cn = wordlist_cn.split(" ");
//12个助记词
if (mnemonicNum == 12) {
seed = entropy.substr(0,32);
var seedBinary = hexToBinary(seed + Crypto.SHA256(Crypto.util.hexToBytes(seed)).substr(0,1));
for (var i = 0; i < 12; i++) {
mnemonic_en.push(wordlist_en[parseInt(seedBinary.substr(i * 11, 11), 2)]);
mnemonic_cn.push(wordlist_cn[parseInt(seedBinary.substr(i * 11, 11), 2)]);
}
}
//24个助记词
else {
if (entropy.length < 64) {
return o;
}
else if (!isHex(entropy.substr(0,64))) {
return o;
}
seed = entropy.substr(0,64);
var seedBinary = hexToBinary(seed + Crypto.SHA256(Crypto.util.hexToBytes(seed)).substr(0,2));
for (var i = 0; i < 24; i++) {
mnemonic_en.push(wordlist_en[parseInt(seedBinary.substr(i * 11, 11), 2)]);
mnemonic_cn.push(wordlist_cn[parseInt(seedBinary.substr(i * 11, 11), 2)]);
}
}
o.seed = seed;
o.mnemonic_en = mnemonic_en.join(" ");
o.mnemonic_cn = mnemonic_cn.join(" ");
return o;
}
function parseMnemonic(mnemonic, language) {
var mnemonic = mnemonic.trim().split(" ");
if (mnemonic.length != 12 && mnemonic.length != 24) {
alert("The mnemonic words are empty or illegal. - 助记词为空或不合法。");
return "";
}
var wordlist_en = "abandon ability able about above absent absorb abstract absurd abuse access accident account accuse achieve acid acoustic acquire across act action actor actress actual adapt add addict address adjust admit adult advance advice aerobic affair afford afraid again age agent agree ahead aim air airport aisle alarm album alcohol alert alien all alley allow almost alone alpha already also alter always amateur amazing among amount amused analyst anchor ancient anger angle angry animal ankle announce annual another answer antenna antique anxiety any apart apology appear apple approve april arch arctic area arena argue arm armed armor army around arrange arrest arrive arrow art artefact artist artwork ask aspect assault asset assist assume asthma athlete atom attack attend attitude attract auction audit august aunt author auto autumn average avocado avoid awake aware away awesome awful awkward axis baby bachelor bacon badge bag balance balcony ball bamboo banana banner bar barely bargain barrel base basic basket battle beach bean beauty because become beef before begin behave behind believe below belt bench benefit best betray better between beyond bicycle bid bike bind biology bird birth bitter black blade blame blanket blast bleak bless blind blood blossom blouse blue blur blush board boat body boil bomb bone bonus book boost border boring borrow boss bottom bounce box boy bracket brain brand brass brave bread breeze brick bridge brief bright bring brisk broccoli broken bronze broom brother brown brush bubble buddy budget buffalo build bulb bulk bullet bundle bunker burden burger burst bus business busy butter buyer buzz cabbage cabin cable cactus cage cake call calm camera camp can canal cancel candy cannon canoe canvas canyon capable capital captain car carbon card cargo carpet carry cart case cash casino castle casual cat catalog catch category cattle caught cause caution cave ceiling celery cement census century cereal certain chair chalk champion change chaos chapter charge chase chat cheap check cheese chef cherry chest chicken chief child chimney choice choose chronic chuckle chunk churn cigar cinnamon circle citizen city civil claim clap clarify claw clay clean clerk clever click client cliff climb clinic clip clock clog close cloth cloud clown club clump cluster clutch coach coast coconut code coffee coil coin collect color column combine come comfort comic common company concert conduct confirm congress connect consider control convince cook cool copper copy coral core corn correct cost cotton couch country couple course cousin cover coyote crack cradle craft cram crane crash crater crawl crazy cream credit creek crew cricket crime crisp critic crop cross crouch crowd crucial cruel cruise crumble crunch crush cry crystal cube culture cup cupboard curious current curtain curve cushion custom cute cycle dad damage damp dance danger daring dash daughter dawn day deal debate debris decade december decide decline decorate decrease deer defense define defy degree delay deliver demand demise denial dentist deny depart depend deposit depth deputy derive describe desert design desk despair destroy detail detect develop device devote diagram dial diamond diary dice diesel diet differ digital dignity dilemma dinner dinosaur direct dirt disagree discover disease dish dismiss disorder display distance divert divide divorce dizzy doctor document dog doll dolphin domain donate donkey donor door dose double dove draft dragon drama drastic draw dream dress drift drill drink drip drive drop drum dry duck dumb dune during dust dutch duty dwarf dynamic eager eagle early earn earth easily east easy echo ecology economy edge edit educate effort egg eight either elbow elder electric elegant element elephant elevator elite else embark embody embrace emerge emotion employ empower empty enable enact end endless endorse enemy energy enforce engage engine enhance enjoy enlist enough enrich enroll ensure enter entire entry envelope episode equal equip era erase erode erosion error erupt escape essay essence estate eternal ethics evidence evil evoke evolve exact example excess exchange excite exclude excuse execute exercise exhaust exhibit exile exist exit exotic expand expect expire explain expose express extend extra eye eyebrow fabric face faculty fade faint faith fall false fame family famous fan fancy fantasy farm fashion fat fatal father fatigue fault favorite feature february federal fee feed feel female fence festival fetch fever few fiber fiction field figure file film filter final find fine finger finish fire firm first fiscal fish fit fitness fix flag flame flash flat flavor flee flight flip float flock floor flower fluid flush fly foam focus fog foil fold follow food foot force forest forget fork fortune forum forward fossil foster found fox fragile frame frequent fresh friend fringe frog front frost frown frozen fruit fuel fun funny furnace fury future gadget gain galaxy gallery game gap garage garbage garden garlic garment gas gasp gate gather gauge gaze general genius genre gentle genuine gesture ghost giant gift giggle ginger giraffe girl give glad glance glare glass glide glimpse globe gloom glory glove glow glue goat goddess gold good goose gorilla gospel gossip govern gown grab grace grain grant grape grass gravity great green grid grief grit grocery group grow grunt guard guess guide guilt guitar gun gym habit hair half hammer hamster hand happy harbor hard harsh harvest hat have hawk hazard head health heart heavy hedgehog height hello helmet help hen hero hidden high hill hint hip hire history hobby hockey hold hole holiday hollow home honey hood hope horn horror horse hospital host hotel hour hover hub huge human humble humor hundred hungry hunt hurdle hurry hurt husband hybrid ice icon idea identify idle ignore ill illegal illness image imitate immense immune impact impose improve impulse inch include income increase index indicate indoor industry infant inflict inform inhale inherit initial inject injury inmate inner innocent input inquiry insane insect inside inspire install intact interest into invest invite involve iron island isolate issue item ivory jacket jaguar jar jazz jealous jeans jelly jewel job join joke journey joy judge juice jump jungle junior junk just kangaroo keen keep ketchup key kick kid kidney kind kingdom kiss kit kitchen kite kitten kiwi knee knife knock know lab label labor ladder lady lake lamp language laptop large later latin laugh laundry lava law lawn lawsuit layer lazy leader leaf learn leave lecture left leg legal legend leisure lemon lend length lens leopard lesson letter level liar liberty library license life lift light like limb limit link lion liquid list little live lizard load loan lobster local lock logic lonely long loop lottery loud lounge love loyal lucky luggage lumber lunar lunch luxury lyrics machine mad magic magnet maid mail main major make mammal man manage mandate mango mansion manual maple marble march margin marine market marriage mask mass master match material math matrix matter maximum maze meadow mean measure meat mechanic medal media melody melt member memory mention menu mercy merge merit merry mesh message metal method middle midnight milk million mimic mind minimum minor minute miracle mirror misery miss mistake mix mixed mixture mobile model modify mom moment monitor monkey monster month moon moral more morning mosquito mother motion motor mountain mouse move movie much muffin mule multiply muscle museum mushroom music must mutual myself mystery myth naive name napkin narrow nasty nation nature near neck need negative neglect neither nephew nerve nest net network neutral never news next nice night noble noise nominee noodle normal north nose notable note nothing notice novel now nuclear number nurse nut oak obey object oblige obscure observe obtain obvious occur ocean october odor off offer office often oil okay old olive olympic omit once one onion online only open opera opinion oppose option orange orbit orchard order ordinary organ orient original orphan ostrich other outdoor outer output outside oval oven over own owner oxygen oyster ozone pact paddle page pair palace palm panda panel panic panther paper parade parent park parrot party pass patch path patient patrol pattern pause pave payment peace peanut pear peasant pelican pen penalty pencil people pepper perfect permit person pet phone photo phrase physical piano picnic picture piece pig pigeon pill pilot pink pioneer pipe pistol pitch pizza place planet plastic plate play please pledge pluck plug plunge poem poet point polar pole police pond pony pool popular portion position possible post potato pottery poverty powder power practice praise predict prefer prepare present pretty prevent price pride primary print priority prison private prize problem process produce profit program project promote proof property prosper protect proud provide public pudding pull pulp pulse pumpkin punch pupil puppy purchase purity purpose purse push put puzzle pyramid quality quantum quarter question quick quit quiz quote rabbit raccoon race rack radar radio rail rain raise rally ramp ranch random range rapid rare rate rather raven raw razor ready real reason rebel rebuild recall receive recipe record recycle reduce reflect reform refuse region regret regular reject relax release relief rely remain remember remind remove render renew rent reopen repair repeat replace report require rescue resemble resist resource response result retire retreat return reunion reveal review reward rhythm rib ribbon rice rich ride ridge rifle right rigid ring riot ripple risk ritual rival river road roast robot robust rocket romance roof rookie room rose rotate rough round route royal rubber rude rug rule run runway rural sad saddle sadness safe sail salad salmon salon salt salute same sample sand satisfy satoshi sauce sausage save say scale scan scare scatter scene scheme school science scissors scorpion scout scrap screen script scrub sea search season seat second secret section security seed seek segment select sell seminar senior sense sentence series service session settle setup seven shadow shaft shallow share shed shell sheriff shield shift shine ship shiver shock shoe shoot shop short shoulder shove shrimp shrug shuffle shy sibling sick side siege sight sign silent silk silly silver similar simple since sing siren sister situate six size skate sketch ski skill skin skirt skull slab slam sleep slender slice slide slight slim slogan slot slow slush small smart smile smoke smooth snack snake snap sniff snow soap soccer social sock soda soft solar soldier solid solution solve someone song soon sorry sort soul sound soup source south space spare spatial spawn speak special speed spell spend sphere spice spider spike spin spirit split spoil sponsor spoon sport spot spray spread spring spy square squeeze squirrel stable stadium staff stage stairs stamp stand start state stay steak steel stem step stereo stick still sting stock stomach stone stool story stove strategy street strike strong struggle student stuff stumble style subject submit subway success such sudden suffer sugar suggest suit summer sun sunny sunset super supply supreme sure surface surge surprise surround survey suspect sustain swallow swamp swap swarm swear sweet swift swim swing switch sword symbol symptom syrup system table tackle tag tail talent talk tank tape target task taste tattoo taxi teach team tell ten tenant tennis tent term test text thank that theme then theory there they thing this thought three thrive throw thumb thunder ticket tide tiger tilt timber time tiny tip tired tissue title toast tobacco today toddler toe together toilet token tomato tomorrow tone tongue tonight tool tooth top topic topple torch tornado tortoise toss total tourist toward tower town toy track trade traffic tragic train transfer trap trash travel tray treat tree trend trial tribe trick trigger trim trip trophy trouble truck true truly trumpet trust truth try tube tuition tumble tuna tunnel turkey turn turtle twelve twenty twice twin twist two type typical ugly umbrella unable unaware uncle uncover under undo unfair unfold unhappy uniform unique unit universe unknown unlock until unusual unveil update upgrade uphold upon upper upset urban urge usage use used useful useless usual utility vacant vacuum vague valid valley valve van vanish vapor various vast vault vehicle velvet vendor venture venue verb verify version very vessel veteran viable vibrant vicious victory video view village vintage violin virtual virus visa visit visual vital vivid vocal voice void volcano volume vote voyage wage wagon wait walk wall walnut want warfare warm warrior wash wasp waste water wave way wealth weapon wear weasel weather web wedding weekend weird welcome west wet whale what wheat wheel when where whip whisper wide width wife wild will win window wine wing wink winner winter wire wisdom wise wish witness wolf woman wonder wood wool word work world worry worth wrap wreck wrestle wrist write wrong yard year yellow you young youth zebra zero zone zoo";
var wordlist_cn = "的 一 是 在 不 了 有 和 人 这 中 大 为 上 个 国 我 以 要 他 时 来 用 们 生 到 作 地 于 出 就 分 对 成 会 可 主 发 年 动 同 工 也 能 下 过 子 说 产 种 面 而 方 后 多 定 行 学 法 所 民 得 经 十 三 之 进 着 等 部 度 家 电 力 里 如 水 化 高 自 二 理 起 小 物 现 实 加 量 都 两 体 制 机 当 使 点 从 业 本 去 把 性 好 应 开 它 合 还 因 由 其 些 然 前 外 天 政 四 日 那 社 义 事 平 形 相 全 表 间 样 与 关 各 重 新 线 内 数 正 心 反 你 明 看 原 又 么 利 比 或 但 质 气 第 向 道 命 此 变 条 只 没 结 解 问 意 建 月 公 无 系 军 很 情 者 最 立 代 想 已 通 并 提 直 题 党 程 展 五 果 料 象 员 革 位 入 常 文 总 次 品 式 活 设 及 管 特 件 长 求 老 头 基 资 边 流 路 级 少 图 山 统 接 知 较 将 组 见 计 别 她 手 角 期 根 论 运 农 指 几 九 区 强 放 决 西 被 干 做 必 战 先 回 则 任 取 据 处 队 南 给 色 光 门 即 保 治 北 造 百 规 热 领 七 海 口 东 导 器 压 志 世 金 增 争 济 阶 油 思 术 极 交 受 联 什 认 六 共 权 收 证 改 清 美 再 采 转 更 单 风 切 打 白 教 速 花 带 安 场 身 车 例 真 务 具 万 每 目 至 达 走 积 示 议 声 报 斗 完 类 八 离 华 名 确 才 科 张 信 马 节 话 米 整 空 元 况 今 集 温 传 土 许 步 群 广 石 记 需 段 研 界 拉 林 律 叫 且 究 观 越 织 装 影 算 低 持 音 众 书 布 复 容 儿 须 际 商 非 验 连 断 深 难 近 矿 千 周 委 素 技 备 半 办 青 省 列 习 响 约 支 般 史 感 劳 便 团 往 酸 历 市 克 何 除 消 构 府 称 太 准 精 值 号 率 族 维 划 选 标 写 存 候 毛 亲 快 效 斯 院 查 江 型 眼 王 按 格 养 易 置 派 层 片 始 却 专 状 育 厂 京 识 适 属 圆 包 火 住 调 满 县 局 照 参 红 细 引 听 该 铁 价 严 首 底 液 官 德 随 病 苏 失 尔 死 讲 配 女 黄 推 显 谈 罪 神 艺 呢 席 含 企 望 密 批 营 项 防 举 球 英 氧 势 告 李 台 落 木 帮 轮 破 亚 师 围 注 远 字 材 排 供 河 态 封 另 施 减 树 溶 怎 止 案 言 士 均 武 固 叶 鱼 波 视 仅 费 紧 爱 左 章 早 朝 害 续 轻 服 试 食 充 兵 源 判 护 司 足 某 练 差 致 板 田 降 黑 犯 负 击 范 继 兴 似 余 坚 曲 输 修 故 城 夫 够 送 笔 船 占 右 财 吃 富 春 职 觉 汉 画 功 巴 跟 虽 杂 飞 检 吸 助 升 阳 互 初 创 抗 考 投 坏 策 古 径 换 未 跑 留 钢 曾 端 责 站 简 述 钱 副 尽 帝 射 草 冲 承 独 令 限 阿 宣 环 双 请 超 微 让 控 州 良 轴 找 否 纪 益 依 优 顶 础 载 倒 房 突 坐 粉 敌 略 客 袁 冷 胜 绝 析 块 剂 测 丝 协 诉 念 陈 仍 罗 盐 友 洋 错 苦 夜 刑 移 频 逐 靠 混 母 短 皮 终 聚 汽 村 云 哪 既 距 卫 停 烈 央 察 烧 迅 境 若 印 洲 刻 括 激 孔 搞 甚 室 待 核 校 散 侵 吧 甲 游 久 菜 味 旧 模 湖 货 损 预 阻 毫 普 稳 乙 妈 植 息 扩 银 语 挥 酒 守 拿 序 纸 医 缺 雨 吗 针 刘 啊 急 唱 误 训 愿 审 附 获 茶 鲜 粮 斤 孩 脱 硫 肥 善 龙 演 父 渐 血 欢 械 掌 歌 沙 刚 攻 谓 盾 讨 晚 粒 乱 燃 矛 乎 杀 药 宁 鲁 贵 钟 煤 读 班 伯 香 介 迫 句 丰 培 握 兰 担 弦 蛋 沉 假 穿 执 答 乐 谁 顺 烟 缩 征 脸 喜 松 脚 困 异 免 背 星 福 买 染 井 概 慢 怕 磁 倍 祖 皇 促 静 补 评 翻 肉 践 尼 衣 宽 扬 棉 希 伤 操 垂 秋 宜 氢 套 督 振 架 亮 末 宪 庆 编 牛 触 映 雷 销 诗 座 居 抓 裂 胞 呼 娘 景 威 绿 晶 厚 盟 衡 鸡 孙 延 危 胶 屋 乡 临 陆 顾 掉 呀 灯 岁 措 束 耐 剧 玉 赵 跳 哥 季 课 凯 胡 额 款 绍 卷 齐 伟 蒸 殖 永 宗 苗 川 炉 岩 弱 零 杨 奏 沿 露 杆 探 滑 镇 饭 浓 航 怀 赶 库 夺 伊 灵 税 途 灭 赛 归 召 鼓 播 盘 裁 险 康 唯 录 菌 纯 借 糖 盖 横 符 私 努 堂 域 枪 润 幅 哈 竟 熟 虫 泽 脑 壤 碳 欧 遍 侧 寨 敢 彻 虑 斜 薄 庭 纳 弹 饲 伸 折 麦 湿 暗 荷 瓦 塞 床 筑 恶 户 访 塔 奇 透 梁 刀 旋 迹 卡 氯 遇 份 毒 泥 退 洗 摆 灰 彩 卖 耗 夏 择 忙 铜 献 硬 予 繁 圈 雪 函 亦 抽 篇 阵 阴 丁 尺 追 堆 雄 迎 泛 爸 楼 避 谋 吨 野 猪 旗 累 偏 典 馆 索 秦 脂 潮 爷 豆 忽 托 惊 塑 遗 愈 朱 替 纤 粗 倾 尚 痛 楚 谢 奋 购 磨 君 池 旁 碎 骨 监 捕 弟 暴 割 贯 殊 释 词 亡 壁 顿 宝 午 尘 闻 揭 炮 残 冬 桥 妇 警 综 招 吴 付 浮 遭 徐 您 摇 谷 赞 箱 隔 订 男 吹 园 纷 唐 败 宋 玻 巨 耕 坦 荣 闭 湾 键 凡 驻 锅 救 恩 剥 凝 碱 齿 截 炼 麻 纺 禁 废 盛 版 缓 净 睛 昌 婚 涉 筒 嘴 插 岸 朗 庄 街 藏 姑 贸 腐 奴 啦 惯 乘 伙 恢 匀 纱 扎 辩 耳 彪 臣 亿 璃 抵 脉 秀 萨 俄 网 舞 店 喷 纵 寸 汗 挂 洪 贺 闪 柬 爆 烯 津 稻 墙 软 勇 像 滚 厘 蒙 芳 肯 坡 柱 荡 腿 仪 旅 尾 轧 冰 贡 登 黎 削 钻 勒 逃 障 氨 郭 峰 币 港 伏 轨 亩 毕 擦 莫 刺 浪 秘 援 株 健 售 股 岛 甘 泡 睡 童 铸 汤 阀 休 汇 舍 牧 绕 炸 哲 磷 绩 朋 淡 尖 启 陷 柴 呈 徒 颜 泪 稍 忘 泵 蓝 拖 洞 授 镜 辛 壮 锋 贫 虚 弯 摩 泰 幼 廷 尊 窗 纲 弄 隶 疑 氏 宫 姐 震 瑞 怪 尤 琴 循 描 膜 违 夹 腰 缘 珠 穷 森 枝 竹 沟 催 绳 忆 邦 剩 幸 浆 栏 拥 牙 贮 礼 滤 钠 纹 罢 拍 咱 喊 袖 埃 勤 罚 焦 潜 伍 墨 欲 缝 姓 刊 饱 仿 奖 铝 鬼 丽 跨 默 挖 链 扫 喝 袋 炭 污 幕 诸 弧 励 梅 奶 洁 灾 舟 鉴 苯 讼 抱 毁 懂 寒 智 埔 寄 届 跃 渡 挑 丹 艰 贝 碰 拔 爹 戴 码 梦 芽 熔 赤 渔 哭 敬 颗 奔 铅 仲 虎 稀 妹 乏 珍 申 桌 遵 允 隆 螺 仓 魏 锐 晓 氮 兼 隐 碍 赫 拨 忠 肃 缸 牵 抢 博 巧 壳 兄 杜 讯 诚 碧 祥 柯 页 巡 矩 悲 灌 龄 伦 票 寻 桂 铺 圣 恐 恰 郑 趣 抬 荒 腾 贴 柔 滴 猛 阔 辆 妻 填 撤 储 签 闹 扰 紫 砂 递 戏 吊 陶 伐 喂 疗 瓶 婆 抚 臂 摸 忍 虾 蜡 邻 胸 巩 挤 偶 弃 槽 劲 乳 邓 吉 仁 烂 砖 租 乌 舰 伴 瓜 浅 丙 暂 燥 橡 柳 迷 暖 牌 秧 胆 详 簧 踏 瓷 谱 呆 宾 糊 洛 辉 愤 竞 隙 怒 粘 乃 绪 肩 籍 敏 涂 熙 皆 侦 悬 掘 享 纠 醒 狂 锁 淀 恨 牲 霸 爬 赏 逆 玩 陵 祝 秒 浙 貌 役 彼 悉 鸭 趋 凤 晨 畜 辈 秩 卵 署 梯 炎 滩 棋 驱 筛 峡 冒 啥 寿 译 浸 泉 帽 迟 硅 疆 贷 漏 稿 冠 嫩 胁 芯 牢 叛 蚀 奥 鸣 岭 羊 凭 串 塘 绘 酵 融 盆 锡 庙 筹 冻 辅 摄 袭 筋 拒 僚 旱 钾 鸟 漆 沈 眉 疏 添 棒 穗 硝 韩 逼 扭 侨 凉 挺 碗 栽 炒 杯 患 馏 劝 豪 辽 勃 鸿 旦 吏 拜 狗 埋 辊 掩 饮 搬 骂 辞 勾 扣 估 蒋 绒 雾 丈 朵 姆 拟 宇 辑 陕 雕 偿 蓄 崇 剪 倡 厅 咬 驶 薯 刷 斥 番 赋 奉 佛 浇 漫 曼 扇 钙 桃 扶 仔 返 俗 亏 腔 鞋 棱 覆 框 悄 叔 撞 骗 勘 旺 沸 孤 吐 孟 渠 屈 疾 妙 惜 仰 狠 胀 谐 抛 霉 桑 岗 嘛 衰 盗 渗 脏 赖 涌 甜 曹 阅 肌 哩 厉 烃 纬 毅 昨 伪 症 煮 叹 钉 搭 茎 笼 酷 偷 弓 锥 恒 杰 坑 鼻 翼 纶 叙 狱 逮 罐 络 棚 抑 膨 蔬 寺 骤 穆 冶 枯 册 尸 凸 绅 坯 牺 焰 轰 欣 晋 瘦 御 锭 锦 丧 旬 锻 垄 搜 扑 邀 亭 酯 迈 舒 脆 酶 闲 忧 酚 顽 羽 涨 卸 仗 陪 辟 惩 杭 姚 肚 捉 飘 漂 昆 欺 吾 郎 烷 汁 呵 饰 萧 雅 邮 迁 燕 撒 姻 赴 宴 烦 债 帐 斑 铃 旨 醇 董 饼 雏 姿 拌 傅 腹 妥 揉 贤 拆 歪 葡 胺 丢 浩 徽 昂 垫 挡 览 贪 慰 缴 汪 慌 冯 诺 姜 谊 凶 劣 诬 耀 昏 躺 盈 骑 乔 溪 丛 卢 抹 闷 咨 刮 驾 缆 悟 摘 铒 掷 颇 幻 柄 惠 惨 佳 仇 腊 窝 涤 剑 瞧 堡 泼 葱 罩 霍 捞 胎 苍 滨 俩 捅 湘 砍 霞 邵 萄 疯 淮 遂 熊 粪 烘 宿 档 戈 驳 嫂 裕 徙 箭 捐 肠 撑 晒 辨 殿 莲 摊 搅 酱 屏 疫 哀 蔡 堵 沫 皱 畅 叠 阁 莱 敲 辖 钩 痕 坝 巷 饿 祸 丘 玄 溜 曰 逻 彭 尝 卿 妨 艇 吞 韦 怨 矮 歇";
wordlist_en = wordlist_en.split(" ");
wordlist_cn = wordlist_cn.split(" ");
var entropy = "";
for (i = 0; i < mnemonic.length; i++) {
if (language == "en") {
binaryStr = wordlist_en.indexOf(mnemonic[i]).toString(2);
var len = binaryStr.length;
if (len < 11) {
for (var j = 0; j < 11 - len; j++) {
binaryStr = "0" + binaryStr;
}
}
entropy = entropy + binaryStr;
}
else {
binaryStr = wordlist_cn.indexOf(mnemonic[i]).toString(2);
var len = binaryStr.length;
if (len < 11) {
for (var j = 0; j < 11 - len; j++) {
binaryStr = "0" + binaryStr;
}
}
entropy = entropy + binaryStr;
}
}
entropy = binaryToHex(entropy);
if (entropy.length == 33) {
if(entropy.substr(32, 1) != Crypto.SHA256(Crypto.util.hexToBytes(entropy.substr(0,32))).substr(0,1)) {
alert("The mnemonic words are illegal. - 助记词不合法。");
return "";
}
entropy = entropy.substr(0,32);
}
else {
if(entropy.substr(64, 2) != Crypto.SHA256(Crypto.util.hexToBytes(entropy.substr(0,64))).substr(0,2)) {
alert("The mnemonic words are illegal. - 助记词不合法。");
return "";
}
entropy = entropy.substr(0,64);
}
return entropy;
}
function hexToBinary(str) {
let result = [];
let list = str.split("");
for (var i = 0; i < list.length; i++) {
let item = list[i];
let binaryStr = parseInt(item,16).toString(2); //进行二进制转化
let len = binaryStr.length;
if (len < 4) {
for (var j = 0; j < 4 - len; j++) {
binaryStr = "0" + binaryStr;
}
}
result.push(binaryStr);
}
return result.join(""); //将拼接后的二进制数组转化为字符串
}
//输入的二进制字符串长度必须是4的整数倍,否则返回空值
function binaryToHex(str) {
if (str.length % 4 != 0) {
return "";
}
var result = "";
for (i = 0; i < str.length / 4; i++) {
result = result + parseInt(str.substr(i * 4, 4), 2).toString(16);
}
return result;
}
function strToBinary(str) {
let result = [];
let list = str.split("");
for (var i = 0; i < list.length; i++) {
let item = list[i];
let binaryStr = item.charCodeAt().toString(2); //进行二进制转化
result.push(binaryStr);
}
return result.join(""); //将拼接后的二进制数组转化为字符串
}
//通过私钥计算公钥及地址时,不能用bitcoin.ECPair.fromWIF()函数,该函数不支持手机端
function priToPub(priBS58C) {
var compressed = true;
var res = Bitcoin.Base58.decode(priBS58C);
if (res.length == 37) {
var compressed = false;
}
var priKey = res.slice(1,33);
var eckey = new Bitcoin.ECKey(priKey);
var pt = getSECCurveByName("secp256k1").getG().multiply(eckey.priv);
eckey.pub = getEncoded(pt, compressed);
return Crypto.util.bytesToHex(eckey.pub);
}
function getEncoded(pt, compressed) {
var x = pt.getX().toBigInteger();
var y = pt.getY().toBigInteger();
var enc = integerToBytes(x, 32);
if (compressed) {
if (y.isEven()) {
enc.unshift(0x02);
} else {
enc.unshift(0x03);
}
} else {
enc.unshift(0x04);
enc = enc.concat(integerToBytes(y, 32));
}
return enc;
}
//用私钥签名
function Sign(message, WIF_priKey) {
var msgHash = Crypto.util.hexToBytes(Crypto.SHA256(Crypto.util.hexToBytes(Crypto.SHA256(Crypto.util.hexToBytes(message)))));
var compressed = true;
var res = Bitcoin.Base58.decode(WIF_priKey);
if (res.length == 37) {
var compressed = false;
}
var priKey = res.slice(1,33);
var eckey = new Bitcoin.ECKey(priKey);
var signature = eckey.sign(msgHash); //签名用的随机私钥k生成过程:在原bicoinjs-lib的SecureRandom()的基础上,再拼接上私钥和待签名交易的哈希值,即k = SHA256(privKey + SHA256(SHA256(message)) + SecureRandom())。由于签名时引入了随机数,对同一信息签名时,每次签名值都发生变化,但每个签名都是有效的。
return signature = Crypto.util.bytesToHex(signature);
}
//用公钥验证签名
function Verify(message, signature, pubKey) {
var msgHash = Crypto.util.hexToBytes(Crypto.SHA256(Crypto.util.hexToBytes(Crypto.SHA256(Crypto.util.hexToBytes(message)))));
signature = Crypto.util.hexToBytes(signature);
if (pubKey.substr(0,2) != "04") {
pubKey = toUncompressedPubkey(pubKey);
}
pubKey=Crypto.util.hexToBytes(pubKey);
var eckey = new Bitcoin.ECKey();
eckey.setPub(pubKey);
eckey.setCompressed(false);
return eckey.verify(msgHash,signature); //eckey.verify()只能用非压缩公钥验证签名。
}
//压缩公钥转换成非压缩公钥
function toUncompressedPubkey(compressedPubkey) {
var x_bn = BigInteger.fromByteArrayUnsigned(Crypto.util.hexToBytes(compressedPubkey.substr(2,64)));
var p = "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f";
var p_bn = BigInteger.fromByteArrayUnsigned(Crypto.util.hexToBytes(p));
//根据模公式,可知y^2 = (x^3 + 7) mod p = (x^3 mod p + 7) mod p
var y_squre = x_bn.pow(3).mod(p_bn).add(BigInteger.fromByteArrayUnsigned([7])).mod(p_bn); //a.pow(b),表示a^b,其中a为BigInteger类,指数b必须是int类型
//根据二次剩余定理,可知y=y_squre^((p+1)/4)mod p
var y = y_squre.modPow(p_bn.add(BigInteger.ONE).divide(BigInteger.fromByteArrayUnsigned([4])),p_bn); //a.modPow(b,c),表示a^b%c,其中a、b、c均为BigInteger类
var prefix = compressedPubkey.substr(0,2);
//如果y的推导值的奇偶性与真实y值的奇偶性不一致,则y在负半轴。
if (y.mod(BigInteger.fromByteArrayUnsigned([2])) != parseInt(prefix)%2) {
y = y.negate().mod(p_bn);
}
return uncompressedPubkey = "04" + compressedPubkey.substr(2, 64) + Crypto.util.bytesToHex(integerToBytes(y, 32));
}
//获取地址余额
function getBalance(addr) {
var addr = addr.trim();
if (addr == "") {
document.getElementById('txBalance').value = "";
return false;
}
var url = document.getElementById('txBalURL').value + addr;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
var balance = myObj[addr]["final_balance"] / 100000000;
document.getElementById('txBalance').value = toNonExponential(balance); //异步执行,与最初的调用程序已无关联,所以无法作为getBalance的返回值
}
else if (this.readyState != 4) {
document.getElementById('txBalance').value = "正在下载"; //异步执行,与最初的调用程序已无关联,所以无法作为getBalance的返回值
}
else {
document.getElementById('txBalance').value = ""; //异步执行,与最初的调用程序已无关联,所以无法作为getBalance的返回值
}
};
//document.getElementById('txBalance').value = 50;
}
//获取UTXO
function getUnspent(addr, UTXO) { //这里的UTXO是解析JSON交易时产生的UTXO(即所选的UTXO)
var addr = addr.trim();
if (addr == "") {
document.getElementById('txUnspent').value = "";
document.getElementById('txUnspentNumArea').value = "";
document.getElementById('txUnspentBalSum').value = "";
return false;
}
var url = document.getElementById('txUnspentURL').value + addr;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById('txUnspent').value = JSON.stringify(myObj, null, '\t');
if (typeof(UTXO) == "undefined") {
var num = myObj["unspent_outputs"].length;
if (num == 1) {
document.getElementById('txUnspentNumArea').value = 1;
}
else if (num > 1) {
document.getElementById('txUnspentNumArea').value = "1-"+myObj["unspent_outputs"].length.toString();
}
else {
document.getElementById('txUnspentNumArea').value = "";
}
var sum = myObj["unspent_outputs"].reduce((a, b) => a + b.value, 0) / 100000000;
document.getElementById('txUnspentBalSum').value = toNonExponential(sum);
}
//解析JSON
else {
var numArea = [];
for (var i = 0; i < UTXO.unspent_outputs.length; i++) {
for (var j = 0; j < myObj.unspent_outputs.length; j++) {
if (myObj.unspent_outputs[j].tx_hash_big_endian == UTXO.unspent_outputs[i].tx_hash_big_endian) {
numArea.push(j + 1);
}
}
}
document.getElementById('txUnspentNumArea').value = numArea.toString();
var sum = getSelUnspent(JSON.stringify(myObj, null, '\t'), numArea.toString()).sum;
document.getElementById('txUnspentBalSum').value = sum;
var txDestValue = document.querySelectorAll('[id="txDestValue"]');
var txDestValueSum = 0;
for (i = 0; i < txDestValue.length; i++) {
txDestValueSum = floatAdd(txDestValueSum, Number(txDestValue[i].value));
}
if (sum.length == 0) {
document.getElementById('txFee').value = "";
} else {
document.getElementById('txFee').value = toNonExponential(Number(floatSub(sum, txDestValueSum)));
}
}
}
else if (this.readyState != 4) {
document.getElementById('txUnspent').value = "正在下载";
document.getElementById('txUnspentNumArea').value = "";
document.getElementById('txUnspentBalSum').value = "";
}
else {
document.getElementById('txUnspent').value = "";
document.getElementById('txUnspentNumArea').value = "";
document.getElementById('txUnspentBalSum').value = "";
}
};
}
//按UTXO余额升序排列
function sortUnspent(unspent) {
var myObj = JSON.parse(unspent);
myObj["unspent_outputs"].sort(function(a,b) {
return a.value - b.value;
})
document.getElementById('txUnspent').value = JSON.stringify(myObj, null, '\t');
var num = myObj["unspent_outputs"].length;
if (num == 1) {
document.getElementById('txUnspentNumArea').value = 1;
}
else if (num > 1) {
document.getElementById('txUnspentNumArea').value = "1-"+myObj["unspent_outputs"].length.toString();
}
else {
document.getElementById('txUnspentNumArea').value = "";
document.getElementById('txUnspentBalSum').value = "";
}
var sum = myObj["unspent_outputs"].reduce((a, b) => a + b.value, 0) / 100000000;
document.getElementById('txUnspentBalSum').value = toNonExponential(sum);
}
//获取所选UTXO及余额之和
function getSelUnspent(unspent, numArea) {
if (unspent == "" || numArea == "") {
var result = {};
result.sum = "";
result.utxo = "";
return result;
}
var numArr = numArea.split(",");
var myObj = JSON.parse(unspent);
var num = 0;
var sum = 0;
var utxo = {};
utxo["unspent_outputs"] = [];
for (var i = 0; i < numArr.length; i++) {
if (numArr[i].indexOf("-") == -1) {
if (isNaN(Number(numArr[i])) || Number(numArr[i]) == 0 || Number(numArr[i]) > myObj["unspent_outputs"].length) {
continue;
}
num = num + 1;
sum = sum + myObj["unspent_outputs"][numArr[i] - 1].value;
utxo["unspent_outputs"][num - 1] = myObj["unspent_outputs"][numArr[i] - 1];
}
else {
numInArr = numArr[i].split("-");
if ((isNaN(Number(numInArr[0])) || Number(numInArr[0]) == 0) && (isNaN(Number(numInArr[1])) || Number(numInArr[1]) == 0)) {
continue;
}
else if (isNaN(Number(numInArr[0])) || Number(numInArr[0]) == 0) {
if (Number(numInArr[1]) > myObj["unspent_outputs"].length) {
continue;
}
num = num + 1;
sum = sum + myObj["unspent_outputs"][numInArr[1] - 1].value;
utxo["unspent_outputs"][num - 1] = myObj["unspent_outputs"][numInArr[1] - 1];
continue;
}
else if (isNaN(Number(numInArr[1])) || Number(numInArr[1]) == 0) {
if (Number(numInArr[0]) > myObj["unspent_outputs"].length) {
continue;
}
num = num + 1;
sum = sum + myObj["unspent_outputs"][numInArr[0] - 1].value;
utxo["unspent_outputs"][num - 1] = myObj["unspent_outputs"][numInArr[0] - 1];
continue;
}
else {
if (Number(numInArr[0]) > Number(numInArr[1]) || Number(numInArr[0]) > myObj["unspent_outputs"].length) {
continue;
}
if (Number(numInArr[1]) > myObj["unspent_outputs"].length) {
numInArr[1] = myObj["unspent_outputs"].length;
}
}
for ( j = numInArr[0]; j <= numInArr[1]; j++) {
num = num + 1;
sum = sum + myObj["unspent_outputs"][j - 1].value;
utxo["unspent_outputs"][num - 1] = myObj["unspent_outputs"][j - 1];
}
}
}
sum = toNonExponential(sum / 100000000);
var result = {};
result.sum = sum;
result.utxo = utxo;
return result;
}
function addDest() {
elem = document.createElement('div');
document.getElementById('newDest').appendChild(elem);
elem.innerHTML = '<div class=h2>【收币地址】</div><textarea id=txDestAddr rows=1 spellcheck=false></textarea><p>收币金额(BTC)</p><textarea id=txDestValue rows=1 spellcheck=false></textarea>';
}
function subDest() {
len = document.getElementById('newDest').childNodes.length;
document.getElementById('newDest').childNodes[len - 1].remove();
}
//将科学计数法转换为小数,JS在处理数值的时候,如果数值小数位数超过6位,就会转换为科学计数法,整数的多于21位也会转为科学计数法。
function toNonExponential(num) {
var m = num.toExponential().match(/\d(?:\.(\d*))?e([+-]\d+)/);
return num.toFixed(Math.max(0, (m[1] || '').length - m[2]));
}
//为构建JSON格式交易做准备,并调用txToJSON()构建JSON格式交易
function txBuildJSON() {
var txNet = document.getElementById('txNet').value;
var txSourceAddr = document.getElementById('txSourceAddr').value;
var txBalance = Number(document.getElementById('txBalance').value);
var txUnspent = document.getElementById('txUnspent').value;
var txUnspentNumArea = document.getElementById('txUnspentNumArea').value;
var txUnspentBalSum = Number(document.getElementById('txUnspentBalSum').value);
var txDestAddr = document.querySelectorAll('[id="txDestAddr"]');
var txDestValue = document.querySelectorAll('[id="txDestValue"]');
var txFee = Number(document.getElementById('txFee').value);
var txLockTime = Number(document.getElementById('txLockTime').value);
var txSequence = Number(document.getElementById('txSequence').value);
var txWitness = "";
//将收币地址和金额,由NodeList转换成Object
var txDest = [];
for (i = 0; i < txDestAddr.length; i++) {
txDest[i] = {};
txDest[i].addr = txDestAddr[i].value;
txDest[i].value = Number(txDestValue[i].value);
}
if (txSourceAddr == "" || txBalance == 0) {
alert("发币地址为空或发币地址没有余额");
return false;
}
if (txUnspentBalSum == 0) {
alert("未选择有效的UTXO");
return false;
}
for (var i = 0; i < txDestAddr.length; i++) {
if (txDestAddr[i].value == "" || Number(txDestValue[i].value) == 0) {
alert("收币地址或收币金额为空");
return false;
}
if (isAddr(txDestAddr[i].value) == false) {
alert("Verification of receiving address failed - 收币地址校验失败");
return false;
}
var str = "13bB"; //bech32地址不区分大小写,但必须要么全都大写或要么全都小写
if (txNet == "mainnet" && (str.indexOf(txSourceAddr.substr(0,1)) == -1 || str.indexOf(txDestAddr[i].value.substr(0,1)) == -1)) {
alert("发币地址或收币地址与所在网络标识不一致,请修改地址或网络标识");
return false;
} else if(txNet != "mainnet" && (str.indexOf(txSourceAddr.substr(0,1)) != -1 || str.indexOf(txDestAddr[i].value.substr(0,1)) != -1)) {
alert("发币地址或收币地址与所在网络标识不一致,请修改地址或网络标识");
return false;
}
//第3个判断条件,是用来判断小数位不能超过8位
if (isNaN(Number(txDestValue[i].value)) || txDestValue[i].value.length - (txDestValue[i].value.indexOf(".") + 1) > 8) {
alert("收币金额无效");
return false;
}
}
//专门用来获取字符串格式的矿工费,因为对于Number()后的科学计数法数值形式,不适用于下面的小数位数判断法
var str_txFee = document.getElementById('txFee').value;
if (txFee == 0 || isNaN(txFee) || str_txFee.length - (str_txFee.indexOf(".") + 1) > 8) {
alert("矿工费为空或无效");
return false;
}
if (isNaN(txLockTime)) {
alert("锁定时间设置无效");
return false;
}
var txDestValueSum = 0;
for (i = 0; i < txDest.length; i++) {
txDestValueSum = floatAdd(txDestValueSum, Number(txDest[i].value));
}
if (txUnspentBalSum < floatAdd(txDestValueSum, txFee)) {
alert("收币金额与矿工费之和大于所选UTXO余额");
return false;
}
//设置找零地址
else if (txUnspentBalSum > floatAdd(txDestValueSum, txFee)) {
var len = txDest.length;
txDest[len] = {};
txDest[len].addr = txSourceAddr;
txDest[len].value = Number(floatSub(txUnspentBalSum, floatAdd(txDestValueSum, txFee)));
}
var version = 1;
var UTXO = getSelUnspent(txUnspent, txUnspentNumArea).utxo;
var sequence = [];
for (var i = 0; i < UTXO.unspent_outputs.length; i++) {
sequence[i] = txSequence;
}
return txToJSON(version, UTXO, sequence, txDest, txWitness, txLockTime, txHashType);
}
////构造JSON格式的交易////////////////////////////////
function txToJSON(version, UTXO, sequence, txDest, txWitness, txLockTime) {
var txJSON = {};
txJSON.hash = "";
txJSON.version = version;
//构建input
txJSON.tx_in_count = UTXO.unspent_outputs.length;
txJSON.tx_in = [];
for (var i = 0; i < txJSON.tx_in_count; i++) {
txJSON.tx_in[i] = {};
txJSON.tx_in[i].previous_output = {};
txJSON.tx_in[i].previous_output.tx_hash_big_endian = UTXO.unspent_outputs[i].tx_hash_big_endian;
txJSON.tx_in[i].previous_output.tx_output_n = UTXO.unspent_outputs[i].tx_output_n;
txJSON.tx_in[i].script_length = Crypto.util.hexToBytes(UTXO.unspent_outputs[i].script).length; //包含OP_LEN
txJSON.tx_in[i].script = UTXO.unspent_outputs[i].script;
txJSON.tx_in[i].sequence = sequence[i];
}
//构建output
txJSON.tx_out_count = txDest.length;
txJSON.tx_out = [];
for (var i = 0; i < txJSON.tx_out_count; i++) {
txJSON.tx_out[i] = {};
txJSON.tx_out[i].value = txDest[i].value;
var addr = txDest[i].addr;
if (addrType(addr) == "P2PK") { //txDest[i].addr中存储的是公钥,解析Raw时用到
var pubKey = addr;
var script = pubKey + " " + "OP_CHECKSIG";
txJSON.tx_out[i].script_length = scriptToBytes(script).buffer.length; //包含OP_LEN
txJSON.tx_out[i].p2pk_script = script;
}
if (addrType(addr) == "P2PKH") {
var hexAddr = Crypto.util.bytesToHex(Bitcoin.Base58.decode(addr)).substr(2,40);
var script = "OP_DUP" + " " + "OP_HASH160" + " " + hexAddr + " " + "OP_EQUALVERIFY" + " " + "OP_CHECKSIG";
txJSON.tx_out[i].script_length = scriptToBytes(script).buffer.length; //包含OP_LEN
txJSON.tx_out[i].p2pkh_script = script;
}
if (addrType(addr) == "P2MS") {
var f = Crypto.util.hexToBytes(addr);
var op_m = findKey(Bitcoin.Opcode.map, f.shift());
var op_n = findKey(Bitcoin.Opcode.map, f[f.length - 2]);
function findKey (obj, value, compare = (a, b) => a === b) {
return Object.keys(obj).find(k => compare(obj[k], value))
}
var script = op_m + " ";
for (i = 0; i < op_n.substr(3); i++) { //substr(start,length)中的length(可选),如果省略了该参数,那么返回从 stringObject 的开始位置到结尾的字串。
var len = readInt(f, 1);
p = Crypto.util.bytesToHex(readBuffer(f, len));
script = script + p + " ";
}
script = script + op_n + " " + "OP_CHECKMULTISIG";
txJSON.tx_out[i].script_length = scriptToBytes(script).buffer.length; //包含OP_LEN
txJSON.tx_out[i].p2pkh_script = script;
}
if (addrType(addr) == "P2SH") {
var hexAddr = Crypto.util.bytesToHex(Bitcoin.Base58.decode(addr)).substr(2,40);
var script = "OP_HASH160" + " " + hexAddr + " " + "OP_EQUAL";
txJSON.tx_out[i].script_length = scriptToBytes(script).buffer.length; //包含OP_LEN
txJSON.tx_out[i].p2sh_script = script;
}
if (addrType(addr) == "P2WPKH" || addrType(addr) == "P2WSH") {
var words = getLibraryFromEncoding('bech32').decode(addr).words;
var hexAddr = Crypto.util.bytesToHex(fromWords(words.slice(1,words.length)));
var script = "0" + " " + hexAddr;
txJSON.tx_out[i].script_length = scriptToBytes(script).buffer.length; //包含OP_LEN
txJSON.tx_out[i].p2wpkh_v0_script = script;
}
}
txJSON.tx_witness = txWitness;
txJSON.lock_time = txLockTime;
//将input的金额附加到最后,签名隔离见证交易时,需要用到输入的金额
txJSON.tx_in_value = "";
for (var i = 0; i < txJSON.tx_in_count; i++) {
//txJSON.tx_in_value = txJSON.tx_in_value + (Array(8).join("0") + UTXO.unspent_outputs[i].value).slice(-8); //将input金额补齐成固定长度8位
txJSON.tx_in_value = txJSON.tx_in_value + " " + UTXO.unspent_outputs[i].value / 100000000;
}
txJSON.tx_in_value = txJSON.tx_in_value.substr(1); //截取字符串中从第二个字符开始到最后一个字符的子串,即删除第一个空格
var j = objClone(txJSON);
j.tx_witness = ""; //计算交易hash(txid)时,去掉witness,Crypto.util.hexToBytes输入为空时,输出是空数组,而不输出0
var raw = txToRaw(JSON.stringify(j, null, '\t'), 1, ""); //1、为了加而加HashType,下一步马上去掉,所以写死“1”;2、因为需要用非隔离见证raw计算txid,所以txScriptType只要不设置成P2SH-P2WPKH或P2SH-P2WSH即可
raw = raw.substr(0, raw.length - 16 * j.tx_in_count); //去掉RAW最后的input金额
raw = raw.substr(0,raw.length - 8); //去掉raw中的HashType,因为计算交易hash(txid)时,不包括HashType
var hash = Crypto.SHA256(Crypto.util.hexToBytes(Crypto.SHA256(Crypto.util.hexToBytes(raw))));
hash = Crypto.util.hexToBytes(hash).reverse();
hash = Crypto.util.bytesToHex(hash);
txJSON.hash = hash;
txJSON.hex_raw_length = raw.length; //计算单位字节花费矿工费sat/vB时用到
return txJSON;
}
////将JSON格式的交易解析为原始输入形式////////////////////////////////
function txParseJSON(txJSON, txNet) {
var txRaw = txToRaw(txJSON, 1, ""); //1、原始输入形式不体现HashType,所以写死“1”;2、ScriptType不影响法币地址计算,所以写死为空
var myObj = txToSource(txRaw, txNet);
var txSourceAddr = myObj.txSourceAddr;
if (txSourceAddr.substr(0, 1) == "0") { //读出来的地址可能是公钥
txSourceAddr = pubKeyToAddr(txSourceAddr, txNet);
}
document.getElementById('txSourceAddr').value = txSourceAddr;
getBalance(txSourceAddr);
//由于getUnspent是异步执行,所以需要先计算转出金额之和,再计算矿工费
var ele = document.getElementById('newDest').childNodes;
var len = ele.length;
for (var i = 0; i < len; i++) {
subDest();
}
var len = myObj.txDest.length;
for (var i = 1; i < len; i++) { //i初始值是1,表示只有当收币地址数量大于1时,才新建地址
addDest();
}
var txDestAddr = document.querySelectorAll('[id="txDestAddr"]');
var txDestValue = document.querySelectorAll('[id="txDestValue"]');
for (var i = 0; i < len; i++) {
var a = myObj.txDest[i].addr;
if (a.substr(0, 1) == "0") { //读出来的地址可能是公钥
a = pubKeyToAddr(a, txNet);
}
txDestAddr[i].value = a;
txDestValue[i].value = toNonExponential(myObj.txDest[i].value);
}
getUnspent(txSourceAddr, myObj.UTXO);
myObj.sequence.sort((a, b) => b - a); //数组降序排列
document.getElementById('txSequence').value = myObj.sequence[0];
document.getElementById('txLockTime').value = myObj.txLockTime;
}
////构造Raw格式的交易////////////////////////////////
function txToRaw(txJSON, txHashType, txScriptType) {
try{
var txJSON = JSON.parse(txJSON);
var arr = [];
arr = arr.concat(Crypto.util.wordsToBytes([txJSON.version]).reverse());
//这是对于已签名的情况;对于未签名的情况,先生成临时txRaw,再用txToSource读出源地址后,进行判断
if (txJSON.tx_witness != "") {
arr = arr.concat(Crypto.util.hexToBytes("0001"));
}
//构建input
arr = arr.concat(Bitcoin.Util.numToVarInt(txJSON.tx_in_count));
for (var i = 0; i < txJSON.tx_in_count; i++) {
arr = arr.concat(Crypto.util.hexToBytes(txJSON.tx_in[i].previous_output.tx_hash_big_endian).reverse()),
arr = arr.concat(Crypto.util.wordsToBytes([txJSON.tx_in[i].previous_output.tx_output_n]).reverse());
arr = arr.concat(Bitcoin.Util.numToVarInt(txJSON.tx_in[i].script_length));
if (txJSON.tx_in[i].script_length != 0) {
arr = arr.concat(Crypto.util.hexToBytes(txJSON.tx_in[i].script));
}
arr = arr.concat(Crypto.util.wordsToBytes([txJSON.tx_in[i].sequence]).reverse());
}
//构建output
arr = arr.concat(Bitcoin.Util.numToVarInt(txJSON.tx_out_count));
for (var i = 0; i < txJSON.tx_out_count; i++) {
//1.由于bitcoin协议规定value的格式是int64,而不是32位(word),所以不能用Crypto.util.wordsToBytes([Math.round(txJSON.tx_out[i].value * 1e8)])。
//2.BigInteger函数支持将Number或String输入转换成大整数,“''+”的目的就是将Math.round(fval * 1e8)的返回数值结果转换成字符串类型。
//3.fval * 1e8将收币金额单位由BTC转换成SAT。
//4.round()函数是四舍五入。
//5.10表示输入的字符串是10进制。
var value = new BigInteger('' + Math.round(txJSON.tx_out[i].value * 1e8), 10);
if (value instanceof BigInteger) {
value = value.toByteArrayUnsigned().reverse();
while (value.length < 8) value.push(0);
}
arr = arr.concat(value);
for (var j in txJSON.tx_out[i]) {
if (j.indexOf("_script") != -1) {
script = txJSON.tx_out[i][j];
}
}
arr = arr.concat(Bitcoin.Util.numToVarInt(txJSON.tx_out[i].script_length));
if (txJSON.tx_out[i].script_length != 0) {
arr = arr.concat(scriptToBytes(script).buffer);
}
}
arr = arr.concat(Crypto.util.hexToBytes(txJSON.tx_witness));
arr = arr.concat(Crypto.util.wordsToBytes([txJSON.lock_time]).reverse());
arr = arr.concat(Crypto.util.wordsToBytes([txHashType]).reverse());
//拼接input金额
var tx_in_value = txJSON.tx_in_value.split(" ");
for (var i = 0; i < tx_in_value.length; i++) {
var value = new BigInteger('' + Math.round(tx_in_value[i] * 1e8), 10);
if (value instanceof BigInteger) {
value = value.toByteArrayUnsigned().reverse();
while (value.length < 8) value.push(0);
}
arr = arr.concat(value);
}
var txRaw = Crypto.util.bytesToHex(arr);
var txSourceAddr = txToSource(txRaw,"mainnet").txSourceAddr; //网络类型不影响对地址类型的判断,所以写死主网
if (txJSON.tx_witness == "" && ((addrType(txSourceAddr) == "P2SH" && (txScriptType == "P2SH-P2WPKH" || txScriptType == "P2SH-P2WSH")) || addrType(txSourceAddr) == "P2WPKH" || addrType(txSourceAddr) == "P2WSH")) {
arr.splice(4, 0, 0, 1); //在index=4的位置,删除0个元素,插入“0, 1”两个元素
txRaw = Crypto.util.bytesToHex(arr);
}
return txRaw;
}catch(err) {
return "error";
}
}
//将Raw格式交易转换成最初的输入形式
function txToSource(txRaw, txNet) {
if (!isHex(txRaw)) {
alert("Raw格式交易不是16进制。");
}
var f = Crypto.util.hexToBytes(txRaw);
var version = readInt(f, 4);
var witnessFlag = 0;
if (f.slice(0,1) == 0) { //通过marker(0x00)就可以判断是否是witness交易,因为tx_in_count不能为0
witnessFlag = 1;
readInt(f, 2); //删除witnessFlag = marker(0x00) + flag(0x01)
}
var UTXO = {};
UTXO.unspent_outputs = [];
var sequence = [];
var tx_in_count = readVarInt(f);
if (tx_in_count instanceof BigInteger || tx_in_count > 0xffff)
return null;
for (var i = 0; i < tx_in_count; i++) {
UTXO.unspent_outputs[i] = {};
UTXO.unspent_outputs[i].tx_hash_big_endian = readHash(f, 32);
UTXO.unspent_outputs[i].tx_output_n = readInt(f, 4);
var s = f.slice(0,f.length); //拷贝一份,为提取源地址做准备,不要用var s = f;因为这表示s与f是同一个变量
var txSourceAddr = readAddr(s, txNet);
UTXO.unspent_outputs[i].script = Crypto.util.bytesToHex(readRawScript(f));
sequence[i] = readInt(f, 4);
}
var txDest = [];
var tx_out_count = readVarInt(f);
if (tx_out_count instanceof BigInteger || tx_out_count > 0xffff)
return null;
for (var i = 0; i < tx_out_count; i++) {
txDest[i] = {};
txDest[i].value = readValue(f);
txDest[i].addr = readAddr(f, txNet);
}
var txWitness = "";
//通过f.length !== 4 && f.length !== 8 && f.length !== 8 + 8 * tx_in_count,来确定是否存在witness签名,
//4指只有锁定时间,8指锁定时间+哈希类型,8 + 8 * tx_in_count指锁定时间+哈希类型+输入金额
if (witnessFlag == 1 && f.length !== 4 && f.length !== 8 && f.length !== 8 + 8 * tx_in_count) {
txWitness = readWitness(f, tx_in_count);
w = Crypto.util.hexToBytes(txWitness);
w.unshift(txWitness.length); //readAddr(f, txNet)函数中,输入的f的第一个元素是脚本长度,所以需要增加witness长度
var txSourceAddr = readAddr(w, txNet);
}
var txLockTime = readInt(f, 4);
var txHashType = readInt(f, 4);
//解析input金额,并添加到UTXO中
for (var i = 0; i < tx_in_count; i++) {
UTXO.unspent_outputs[i].value = readValue(f) * 100000000;
}
var res = {};
res.txSourceAddr = txSourceAddr;
res.version = version;
res.UTXO = UTXO;
res.sequence = sequence;
res.txDest = txDest;
res.txWitness = txWitness;
res.txLockTime =txLockTime;
res.txHashType = txHashType;
return res;
}
//将Raw格式交易解析成JSON格式,并把HashType解析出来
function txParseRaw(txRaw) {
var s = txToSource(txRaw, "mainnet"); //JSON格式不体现主网还是测试网,所以写死主网
var txJSON = txToJSON(s.version, s.UTXO, s.sequence, s.txDest, s.txWitness, s.txLockTime);
var res = {};
res.txJSON = txJSON;
res.txHashType = s.txHashType;
return res;
}
function txToSignedRaw(txRaw, txPriKey, txScriptType) {
if (txRaw == "" || txPriKey == "") {
alert("待签名的Raw交易字符串或私钥不能为空");
return false;
}
witnessFlag = 0;
if (txRaw.substr(8,4) == "0001") {
witnessFlag = 1;
}
var txJSON = txParseRaw(txRaw).txJSON;
var txHashType = txParseRaw(txRaw).txHashType;
if ((parseInt(txJSON.tx_in[0].script.substr(0,2), 16) <= 0x49 && parseInt(txJSON.tx_in[0].script.substr(2,2), 16) == 0x30) || (parseInt(txJSON.tx_in[0].script.substr(0,2), 16) ==0 && (parseInt(txJSON.tx_in[0].script.substr(2,2), 16) <= 0x49 && parseInt(txJSON.tx_in[0].script.substr(4,2), 16) == 0x30)) || txJSON.tx_witness != "") {
alert("Raw交易字符串已经签名");
return false;
}
txJSON.tx_witness = "";
var jsonForSign = objClone(txJSON);
for (var i = 0; i < txJSON.tx_in_count; i++) {
var raw = txRawForSign(jsonForSign, i, txHashType, txScriptType, txPriKey);
var sign = Crypto.util.hexToBytes(Sign(raw, txPriKey)); //由于引入了随机数,每次签名结果都不一样,但都是有效的
sign.push(parseInt(txHashType, 10)); //签名类型附在签名之后(占1个字节)
sign = Crypto.util.bytesToHex(sign);
var script = [];
script = script.concat(Bitcoin.Util.numToVarInt(txJSON.tx_in[i].script_length));
script = script.concat(Crypto.util.hexToBytes(txJSON.tx_in[i].script));
var aType = addrType(readAddr(script)); //readAdr()会修改script的内容,所以在if()条件判断中只能执行一次
if (aType == "P2PK") {
var script = scriptToBytes(sign);
txJSON.tx_in[i].script_length = script.buffer.length;
txJSON.tx_in[i].script = Crypto.util.bytesToHex(script.buffer);
if (witnessFlag == 1) {
txJSON.tx_witness = txJSON.tx_witness + "00";
}
}
else if (aType == "P2PKH") {
var script = scriptToBytes(sign + " " + priToPub(txPriKey));
txJSON.tx_in[i].script_length = script.buffer.length;
txJSON.tx_in[i].script = Crypto.util.bytesToHex(script.buffer);
if (witnessFlag == 1) {
txJSON.tx_witness = txJSON.tx_witness + "00";
}
}
else if (aType == "P2MS") {
alert("程序暂不支持多重签名");
}
else if (aType == "P2SH") { //p2sh,输入私钥数量为1,则不是多重签名
if (txScriptType == "P2SH-P2PK") {
var redeemScript = Crypto.util.bytesToHex(scriptToBytes(priToPub(txPriKey) + " " + "OP_CHECKSIG").buffer);
var script = scriptToBytes(sign + " " + redeemScript);
txJSON.tx_in[i].script_length = script.buffer.length;
txJSON.tx_in[i].script = Crypto.util.bytesToHex(script.buffer);
if (witnessFlag == 1) {
txJSON.tx_witness = txJSON.tx_witness + "00";
}
}
else if (txScriptType == "P2SH-P2PKH") {
var redeemScript = Crypto.util.bytesToHex(scriptToBytes("OP_DUP" + " " + "OP_HASH160" + " " + Crypto.RIPEMD160(Crypto.util.hexToBytes(Crypto.SHA256(Crypto.util.hexToBytes(priToPub(txPriKey))))) + " " + "OP_EQUALVERIFY" + " " + "OP_CHECKSIG").buffer);
var script = scriptToBytes(sign + " " + priToPub(txPriKey) + " " + redeemScript);
txJSON.tx_in[i].script_length = script.buffer.length;
txJSON.tx_in[i].script = Crypto.util.bytesToHex(script.buffer);
if (witnessFlag == 1) {
txJSON.tx_witness = txJSON.tx_witness + "00";
}
}
if (txScriptType == "P2SH-P2MS") {
alert("程序暂不支持多重签名");
}
else if (txScriptType == "P2SH-P2WPKH") {
var redeemScript = Crypto.util.bytesToHex(scriptToBytes("OP_0" + " " + Crypto.RIPEMD160(Crypto.util.hexToBytes(Crypto.SHA256(Crypto.util.hexToBytes(priToPub(txPriKey)))))).buffer);
var script = scriptToBytes(redeemScript);
txJSON.tx_in[i].script_length = script.buffer.length;
txJSON.tx_in[i].script = Crypto.util.bytesToHex(script.buffer);
txJSON.tx_witness = txJSON.tx_witness + "02" + Crypto.util.bytesToHex(scriptToBytes(sign + " " + priToPub(txPriKey)).buffer);