This repository has been archived by the owner on Mar 2, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
NEMApiLibrary.php
1549 lines (1499 loc) · 62.5 KB
/
NEMApiLibrary.php
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
<?php
/*
* NEM API Library Ver 1.13 Alpha
*/
class TransactionBuilder{
// NEM用トランザクション操作
public $version_ver1;
public $version_ver2;
public $net;
public $recipient;
public $amount; // 小数点アリ
public $fee; // 小数点アリ
public $message = '';
public $payload;
public $type = 257;
private $pubkey;
private $prikey;
private $baseurl;
public $mosaic;
public function __construct($net = 'mainnet') {
if($net === 'mainnet'){
$this->version_ver1 = 1744830465;
$this->version_ver2 = 1744830466;
}elseif($net === 'testnet'){
$this->version_ver1 = -1744830463;
$this->version_ver2 = -1744830462;
}else{
throw new Exception("Error:net parameter isn't set ,net is mainnet or testnet.");
}
$this->net = $net;
}
public function setting($NEMpubkey,$NEMprikey,$baseurl = 'http://localhost:7890'){
$this->pubkey = $NEMpubkey;
$this->prikey = $NEMprikey;
$this->baseurl = $baseurl;
}
private function check($amountCheck = true){
if(empty($this->version_ver1) OR empty($this->version_ver2)){
throw new Exception("Error:version isn't set.");
}
if(empty($this->recipient)){
throw new Exception("Error:recipient address isn't set.");
}
if(!isset($this->amount) AND $amountCheck){
throw new Exception("Error:amount isn't set.");
}
if(!isset($this->fee)){
throw new Exception("Error:fee isn't set.");
}
}
public function nodelist(){
if($this->net === 'mainnet'){
return array('62.75.171.41','104.251.212.131','45.124.65.125','185.53.131.101');
}else{
return array('104.128.226.60','23.228.67.85');
}
}
public function InputMosaic($namespace,$name,$amount){
/* $mosaic内は以下のような配列
[ makoto.metals.silver:coinを1COIN(1桁)、nem:xemを100XEM(6桁)を送る場合
{
"quantity": 10,
"mosaicId": {
"namespaceId": "makoto.metals.silver",
"name": "coin"
}
},
{
"quantity": 100000000,
"mosaicId": {
"namespaceId": "nem",
"name": "xem"
}
}
]
*/
if(SerchMosaicInfo($this->baseurl,$namespace, $name)){
$mosaic_tmp = array(
"quantity" => $amount, // 小数点無しの生の値
"mosaicId" => array(
"namespaceId" => $namespace,
"name" => $name
)
);
$mosaic = $this->mosaic;
$mosaic[] = $mosaic_tmp;
$this->mosaic = $mosaic;
return TRUE;
}else{
// Mosaicの定義が不明
return FALSE;
}
}
public function SendNEMver1($send = true){
// NEMを$addressへ送る,Non-mosaic
// 返り値はTXID、失敗時はFalse
$url = $this->baseurl ."/transaction/prepare-announce";
$this->check();
$POST_DATA =
array('transaction'=> array(
'timeStamp'=> (time() - 1427587585), // NEMは1427587585つまり2015/3/29 0:6:25 UTCスタート
'amount' => $this->amount * 1000000, // NEMは小数点以下6桁まで有効
'fee' => $this->fee *1000000,
'recipient'=> $this->recipient ,
'type' => $this->type ,
'deadline' => (time() - 1427587585 + 43200), // 送金の期限
'message'=> array(
'payload' => isset($this->payload) ? $this->payload : bin2hex($this->message) ,
'type' => 1
),
'version' => $this->version_ver1 , // mainnetは-1744830465、testnetは-1744830463
'signer' => $this->pubkey // signer サイン主のこと
),
'privateKey' => $this->prikey
);
// testnetは-1744830462だと以下のエラーが出る
// expected value for property mosaics, but none was found これはNEMをモザイクとして送金する必要があるということ?
//print_r($POST_DATA);print "<BR>"; // debug
if($send){
return get_POSTdata($url, json_encode($POST_DATA));
}else{
return $POST_DATA;
}
// 返り値 Array ( [innerTransactionHash] => Array ( )
// [code] => 1
// [type] => 1
// [message] => SUCCESS
// [transactionHash] => Array (
// [data] => 208a41fb815cc0dd6173213a031ba6f956ef60b6530c255a2926e9a8555198e2 )
// )
// 返り値(error) Array ( [timeStamp] => 55043675
// [error] => Not Found
// [message] => invalid address 'TB235JLAOGALDATDJC7LXDMZSDMFBUMDVIBFVQ' (org.nem.core.model.Address)
// [status] => 404 )
}
public function SendMosaicVer2($send = true){
// Mosaic送信用Ver2のトランザクション生成
// 返り値はTXID、失敗時はFalse
$mosaic = $this->mosaic;
$url = $this->baseurl ."/transaction/prepare-announce";
$this->check(false);
$POST_DATA =
array(
'transaction'=>array(
'timeStamp' => (time() - 1427587585),
'amount' => 1 * 1000000, // 実際には1XEM取られない
'fee' => $this->fee * 1000000,
'recipient' => $this->recipient ,
'type' => $this->type ,
'deadline' => (time() - 1427587585 + 43200),
'message' => array(
'payload' => isset($this->payload) ? $this->payload : bin2hex($this->message) ,
'type' => 1
),
'version' => $this->version_ver2, // Testnetは-1744830462 ,mainnetは-1744830466
'signer' => $this->pubkey,
'mosaics' => $mosaic,
),
'privateKey'=>$this->prikey
);
if($send){
return get_POSTdata($url, json_encode($POST_DATA));
}else{
return $POST_DATA;
}
}
public function EstimateFee(){
// 送金に必要なFeeを計算し返す
$mosaic = $this->mosaic;
if(is_array($mosaic)){
// With-mosaic
$fee_tmp = 0;
foreach ($mosaic as $mosaicValue) {
$quantity = $mosaicValue['quantity'];
$namespace = $mosaicValue['mosaicId']['namespaceId'];
$name = $mosaicValue['mosaicId']['name'];
$DetailMosaic = SerchMosaicInfo($this->baseurl,$namespace, $name);
if(!$DetailMosaic){ return FALSE;}
if($DetailMosaic['initialSupply'] <= 10000 AND $DetailMosaic['divisibility'] === 0){
// SmallBusinessMosaic
// 分割0でSupply1万以下のMosaicは"SmallBusinessMosaic"と呼ばれFeeが安いぞぃ
$fee_tmp += 1;
}else{
// Others
// http://mijin.io/forums/forum/日本語/off-topics/717-雑談のお部屋?p=1788#post1788
//
$initialSupplybyUnit = $DetailMosaic['initialSupply'] * pow(10, $DetailMosaic['divisibility']);
// initialSupply は何故か小数点無しの生の値ではない(謎
$fee_tmp += round( max(1, min(25, $quantity * 900000 / $initialSupplybyUnit ) - floor(0.8 * log(9000000000000000 / $initialSupplybyUnit ))));
}
// 徴収されるNEMやモザイクは含めなくてもよい、NISが勝手に引いてくれる
} // end of foreach ($mosaic as $mosaicValue) {
$fee = $fee_tmp;
}else{
// Non-mosaic
$fee_tmp = floor($this->amount / 10000);
if($fee_tmp < 1){
$fee = 1;
}elseif($fee_tmp < 26){
$fee = $fee_tmp;
}else{
$fee = 25;
}
}// end of Non-mosaic
if(isset($this->payload)){
if(!preg_match('/^fe([0-9abcdefABCDEF]+)/', $this->payload, $matches)){
throw new Exception("payload must begin with 'fe' and consist of hex code, for example 'fe01234567890abcdef' is OK.");
}
$fee_tmp = floor(strlen($matches[1]) / 32 /2) + 1;
}elseif(strlen($this->message) > 0){ // messageのFee
$fee_tmp = floor(strlen($this->message) / 32) + 1;
}else{
$fee_tmp = 0;
}
$fee += $fee_tmp;
$this->fee = $fee;
return $fee;
}
public function EstimateLevy(){
// 徴収Mosaic
$mosaic = $this->mosaic;
// $return はkeyにnamespace:name,valueに小数点無しの生の値
foreach ($mosaic as $mosaicValue) {
$quantity = $mosaicValue['quantity'];
$namespace = $mosaicValue['mosaicId']['namespaceId'];
$name = $mosaicValue['mosaicId']['name'];
$MosaicData = SerchMosaicInfo($this->baseurl,$namespace, $name);
if(!$MosaicData){ return FALSE;}
$levy = $MosaicData['detail']['mosaic']['levy'];
if(empty($levy)){
continue;
}else{
// 徴収アリ
if($levy['type'] === 1){
// Type1:定額徴収
$fee_tmp = $levy['fee'];
}elseif($levy['type'] === 2){
// Type2:%徴収
// 100000 * 48 / 10000 = 480
// 123456 * 44 / 10000 = 543
$fee_tmp = floor($levy['fee'] * $quantity / 10000);
}
if(isset($return["{$levy['mosaicId']['namespaceId']}:{$levy['mosaicId']['name']}"])){
$return["{$levy['mosaicId']['namespaceId']}:{$levy['mosaicId']['name']}"] += $fee_tmp;
}else{
$return["{$levy['mosaicId']['namespaceId']}:{$levy['mosaicId']['name']}"] = $fee_tmp;
}
// 徴収尾張
}
}
return $return;
}
public function ImportAddr($address){
$tmp = str_replace('-', '', $address);
$tmp = trim($tmp);
$this->recipient = $tmp;
}
public function analysis($reslt){
if(isset($reslt['message']) AND $reslt['message'] === 'SUCCESS'){
return array('status' => TRUE, 'txid' => $reslt['transactionHash']['data']);
}else{
return array('status' => FALSE, 'message' => $reslt['message'] );
}
}
public function GetTX($txid){
// TXIDのみから取引情報を取得可能。
// ただし36時間以上経過した取引情報について
// すべてのノードで取得できるわけではない模様。
// NIS API Doc にはないので注意
// 設定を変えるとローカルでも使える→ nis.transactionHashRetentionTime = -1
$nodelist = $this->nodelist();
foreach ($nodelist as $nodelistValue) {
$url = 'http://' .$nodelistValue. ':7890/transaction/get?hash=' .$txid;
$data = get_json_array($url);
if($data){
return $data;
}else{
continue;
}
}
return FALSE;
}
public static function PubKey2Addr($PubKey,$baseurl = 'http://localhost:7890'){
// 公開鍵からアドレスへ変換
if(CasheGet($PubKey)){
$data = CasheGet($PubKey);
}else{
$url = $baseurl .'/account/get/from-public-key?publicKey='.$PubKey;
$data = get_json_array($url);
CasheInsert($PubKey, $data);
}
if($data){
return $data['account']['address'];
}else{
return FALSE;
}
}
public static function Addr2PubKey($address,$baseurl = 'http://localhost:7890'){
// アドレスから公開鍵へ変換
$Addr_tmp = trim(str_replace('-', '', $address));
if(CasheGet($Addr_tmp)){
$data = CasheGet($Addr_tmp);
}else{
$url = $baseurl .'/account/get/forwarded?address=' . $Addr_tmp;
$data = get_json_array($url);
CasheInsert($Addr_tmp, $data);
}
if($data === array()){
return "";
}elseif($data === false){
return false;
}else{
return $data['account']['publicKey'];
}
/*
}
if(isset($data['account']['publicKey'])){
return $data['account']['publicKey'];
}else{
return FALSE;
}
*/
}
}
class Multisig {
public $version_ver1;
public $version_ver2;
public $net;
public $recipient;
public $amount; // 小数点アリ
public $fee; // 小数点アリ
public $message = '';
public $payload;
public $deadline = 43200; // 60*60*24
private $pubkey;
private $prikey;
private $baseurl;
public $mosaic;
public function __construct($pubkey,$prikey,$baseurl = 'http://localhost:7890') {
$this->pubkey = $pubkey;
$this->prikey = $prikey;
$this->baseurl = $baseurl;
}
public function set_net($net = 'mainnet'){
if(in_array($net, array('mainnet','testnet'),TRUE)){
$this->net = $net;
$this->version_ver1 = ($net === 'mainnet')? 1744830465 : -1744830463 ;
$this->version_ver2 = ($net === 'mainnet')? 1744830466 : -1744830462 ;
}else{
throw new Exception('$net must be mainnet or testnet.');
}
}
public function CreateAddr($OtherPubKeys,$require,$send = true){
/* マルチシグアドレスを署名者に加えることはできないので注意
* $OtherPubKeys に署名者のPubkeyを、$requireに必要署名数
*/
if(isset($OtherPubKeys)){
$all_acounts = count($OtherPubKeys);
if($all_acounts < $require){
throw new Exception('Required cosignatories is more than input cosignatories');
}
if(!isset($this->net)){
throw new Exception('Do function net_set before function CreateAddr.');
}
foreach ($OtherPubKeys as $OtherPubKeysValue) {
$modifications[] = array(
'modificationType' => 1, // 1は加える、2は削除、7.5Adding and removing cosignatoriesと同じ
'cosignatoryAccount' => $OtherPubKeysValue
);
if($OtherPubKeysValue === $this->pubkey){
throw new Exception('Multisig account is same as a cosignator');
// FAILURE_MULTISIG_ACCOUNT_CANNOT_BE_COSIGNER → 署名者が既にマルチシグアドレス
}
}
$url = $this->baseurl ."/transaction/prepare-announce";
$this->fee = 16 + 6 * $all_acounts;
$POST_DATA =
array(
'transaction' => array(
'timeStamp' => (time() - 1427587585),
'fee' => $this->fee * 1000000,
'type' => 4097,
'deadline' => (time() - 1427587585 + 43200),
'version' => $this->version_ver2,
'signer' => $this->pubkey,
'modifications' => $modifications,
'minCosignatories' => array(
'relativeChange' => $require
)
),
'privateKey' => $this->prikey
);
if($send){
// P2Pネットワークへ流す
return get_POSTdata($url, json_encode($POST_DATA));
}else{
// P2Pネットワークへ流さずにFeeを返す
return array('data' => $POST_DATA,'fee' => $this->fee);
}
}else{
throw new Exception('Set publickeys on $OtherPubKeys as array');
}
}
public function InitialTX($otherTrans,$send = true){
/* マルチシグトランザクションの起こり
* 最初にTXを作成した人がinnerTransactionHashのFeeを払う
*/
$url = $this->baseurl ."/transaction/prepare-announce";
/* これは例、トランザクションの入れ子がマルチシグ
* innerTransactionHashとはコレのこと
$otherTrans = array(
'timeStamp' => (time() - 1427587585),
'amount' => $this->amount * 1000000,
'fee' => $this->fee * 1000000,
'recipient' => $this->recipient,
'type' => 257,
'deadline' => (time() - 1427587585 + $this->deadline),
'message' => array(
'payload' => isset($this->payload)? $this->payload : bin2hex($this->message),
'type' => 1
),
'version' => $this->version_ver1,
'signer' => $a
);
*/
$POST_DATA =
array(
'transaction' => array(
'timeStamp' => (time() - 1427587585),
'fee' => 6 * 1000000, // baseは6XEM、手数料はマルチシグアドレスより支払われる
'type' => 4100,
'deadline' => (time() - 1427587585 + $this->deadline),
'version' => $this->version_ver1,
'signer' => $this->pubkey,
'otherTrans' => $otherTrans,
'signatures' => array() // ここにcosignerの署名が入る
),
'privateKey' => $this->prikey
);
if($send){
// P2Pネットワークへ流す
return get_POSTdata($url, json_encode($POST_DATA));
}else{
// P2Pネットワークへ流さずにTXDATAを返す
return array('data' => $POST_DATA,'fee' => 6);
}
}
public function CosignTX($MultisigPubkey,$innerTransactionHash,$send = true){
/* 流れてきたマルチシグトランザクションに署名
* $innerTransactionHashは/account/unconfirmedTransactions?address=で取得できるmetaのdata
* 署名者にはFeeはかからない
*/
$url = $this->baseurl ."/transaction/prepare-announce";
$POST_DATA =
array(
'transaction' => array(
'timeStamp' => (time() - 1427587585),
'fee' => 6 * 1000000, // 追加署名する人は払わなくても良い
'type' => 4098,
'deadline' => (time() - 1427587585 + $this->deadline),
'version' => $this->version_ver1,
'signer' => $this->pubkey,
'otherHash' => array('data' => $innerTransactionHash),
'otherAccount' => TransactionBuilder::PubKey2Addr($MultisigPubkey, $this->baseurl),
),
'privateKey' => $this->prikey
);
if($send){
// P2Pネットワークへ流す
return get_POSTdata($url, json_encode($POST_DATA));
}else{
// P2Pネットワークへ流さずにTXDATAを返す
return array('data' => $POST_DATA,'fee' => 0);
}
}
public function ModifiMultisig($MultisigPubkey,$ADDpubkey = array(),$REMpubkey = array(),$relativeChange = 0,$send = TRUE){
/* Add or Remove multisig
* $ADDpubkeyに署名者に加えるPubkey、$REMpubkeyに署名者から除外するPubkey
* $relativeChangeに必要署名数を相対的に変更
* Feeはマルチシグアドレスより引かれる
* 注意点、minCosignatories のみ 変更はできない(バグかも
*/
$fee = 10 + ( count($ADDpubkey) + count($REMpubkey) ) * 6; // 10XEMをベースに1人を変更するたびに6XEM加算
if($relativeChange !== 0){ $fee += 6; } // 必要署名数を変更で6XEM加算
$url = $this->baseurl .'/account/get/forwarded/from-public-key?publicKey='. $MultisigPubkey ;
$tmp = get_json_array($url);
if(count($tmp['meta']['cosignatories']) === 0){
throw new Exception($MultisigPubkey .' isn\t MultisigAddress.');
}
$minCosignatories = $tmp['account']['multisigInfo']['minCosignatories'];
$otherTrans =
array(
'timeStamp' => (time() - 1427587585),
'fee' => $fee * 1000000,
'type' => 4097,
'deadline' => (time() - 1427587585 + $this->deadline),
'version' => (count($ADDpubkey) + count($REMpubkey) > 0)? $this->version_ver1 : $this->version_ver2 ,
'signer' => $MultisigPubkey
);
if( $relativeChange !== 0){
$otherTrans['minCosignatories']['relativeChange'] = $relativeChange;
}
$otherTrans['modifications'] = array();
if( isset($ADDpubkey) ){
foreach ($ADDpubkey as $ADDpubkeyValue) {
$otherTrans['modifications'][] = array(
'modificationType' => 1,
'cosignatoryAccount' => $ADDpubkeyValue
);
} }
if( isset($REMpubkey) ){
foreach ($REMpubkey as $REMpubkeyValue) {
$otherTrans['modifications'][] = array(
'modificationType' => 2,
'cosignatoryAccount' => $REMpubkeyValue
);
} }
$POST_DATA =
array(
'transaction' => array(
'timeStamp' => (time() - 1427587585),
'fee' => 6 * 1000000, // 追加署名する人は払わなくても良い
'type' => 4100,
'deadline' => (time() - 1427587585 + $this->deadline),
'version' => $this->version_ver1,
'signer' => $this->pubkey,
'otherTrans'=> $otherTrans,
'signatures'=> array()
),
'privateKey' => $this->prikey
);
if($send){
// P2Pネットワークへ流す
$url = $this->baseurl ."/transaction/prepare-announce";
return get_POSTdata($url, json_encode($POST_DATA));
}else{
// P2Pネットワークへ流さずにTXDATAを返す
return array('data' => $POST_DATA,'fee' => $fee + $minCosignatories * 6);
}
}
public static function checkMultisigTX($pubkey,$baseurl = 'http://localhost:7890'){
/* 自分のアドレスにマルチシグ署名依頼が来ていないか調べる。
* cronで定期実行するとよいと思います。Multisig::checkMultisigTX($NEMAddress, $pubkey)
*/
$Addr = TransactionBuilder::PubKey2Addr($pubkey, $baseurl);
$url = $baseurl .'/account/unconfirmedTransactions?address=' . $Addr;
$data = get_json_array($url);
$reslt = array();
if(!isset($data['data'])){
return $reslt;
}
foreach ($data['data'] as $dataValue) {
$innerTransactionHash = $dataValue['meta']['data'];
$timeStamp = $dataValue['transaction']['timeStamp'] + 1427587585;
$type = $dataValue['transaction']['type'];
$deadline = $dataValue['transaction']['deadline'] + 1427587585;
$signers = count($dataValue['transaction']['signatures']); // 既に署名した人の数
$otherTrans = $dataValue['transaction']['otherTrans']; // マルチシグで送金される内容
foreach ($dataValue['transaction']['signatures'] as $SignaturesValue) {
if($SignaturesValue['signer'] === $pubkey){
// 既にあなたは署名済み
continue;
}
}
if($type === 4100 ){
// まだ署名していないマルチシグTX
$reslt[] = array('innerTransactionHash' => $innerTransactionHash,
'timeStamp' => $timeStamp,
'deadline' => $deadline,
'signers' => $signers,
'otherTrans' => $otherTrans);
}else{
continue;
}
return $reslt;
}
}
public function analysis($reslt){
if(isset($reslt['message']) AND $reslt['message'] === 'SUCCESS'){
return array('status' => TRUE, 'txid' => $reslt['transactionHash']['data'],
'inner_txid' => isset($reslt['innerTransactionHash']['data'])? $reslt['innerTransactionHash']['data'] : NULL );
}else{
return array('status' => FALSE, 'message' => $reslt['message'] );
}
}
}
class Apostille {
// アポスティーユ作成
public $payload ;
public $algo ;
public $type ;
public $net;
public $filename ;
public $recipient;
public $txid;
public function __construct($filename = NULL) {
if(isset($filename)){
$this->setting($filename);
}
}
public function set_net($net){
if(!in_array($net, array('mainnet','testnet'),true)){
throw new Exception ("Error:parameter of net ,mainnet or testnet are allowd.");
}
$type = $this->type;
$this->net = $net;
if($net === 'mainnet'){
//$this->version = -1744830465;
$this->recipient = ($type === 'public')?'NCZSJHLTIMESERVBVKOW6US64YDZG2PFGQCSV23J':'NAX4LLSZ7N3JHWQYQSAMGABTD5SVHFEJD2BTWQBN';
}else{
//$this->version = -1744830463;
$this->recipient = ($type === 'public')?'TC7MCY5AGJQXZQ4BN3BOPNXUVIGDJCOHBPGUM2GE':'TDXJZ42QNFCGEZVCZFZSE2QPKQU7MDZ4SNO6NOI4';
}
}
public function setting($filename,$type = 'public',$algo = 'sha256',$net = 'mainnet'){
if(!preg_match('/^(.+?)(\.[^.]+?)$/', $filename)){
throw new Exception("Error:$filename ファイルに拡張子を加えて下さい。");
}
$this->filename = $filename;
$this->type = $type;
$this->algo = $algo;
if(!file_exists($filename)){
throw new Exception ("Error:$filename isn't exist.");
}
if(!in_array($type, array('public','private'),true)){
throw new Exception ("Error:parameter of type ,public or private are allowd.");
}
if(!in_array($algo, array('md5','sha1','sha256','sha3-256','sha3-512'),true)){
throw new Exception ("Error:parameter of algo ,md5 ,sha1 ,sha256 or keccak(SHA3) are allowd.");
}
$this->set_net($net);
}
public function Run(){
/* https://github.com/strawbrary/php-sha3
* SHA3のハッシュはこのモジュールを導入
* 下部にSHA3のハッシュ化classを置いてあるがかなり遅い
* 参考メモ
* PATHを通していない場合→/opt/lampp/bin/phpize
* ./configure --enable-sha3 --with-php-config=/opt/lampp/bin/php-config
* cp /modules/sha3.so /opt/lampp/lib/php/extensions/no-debug-non-zts-20121212/
*/
$hex = 'fe'; // 形式 HEX
switch ($this->algo) {
case 'md5' : $algo = 1; break;
case 'sha1' : $algo = 2; break;
case 'sha256' : $algo = 3; break;
case 'sha3-256' : $algo = 8; break;
case 'sha3-512' : $algo = 9; break;
default:throw new Exception ("Error:未対応の暗号方式です。");
}
if($algo < 4){
$hash = hash_file($this->algo, $this->filename);
}elseif($algo === 8){
$all = file_get_contents($this->filename);
//$hash = sha3($all,256);
set_time_limit(250);
$hash = Sha3_0xbb::hash($all, 256 );
set_time_limit(30);
}elseif($algo === 9){
$all = file_get_contents($this->filename);
//$hash = sha3($all,512);
set_time_limit(250);
$hash = Sha3_0xbb::hash($all, 512 );
set_time_limit(30);
}else{
die("Error:$algo が例外です。");
}
if($this->type === 'public'){
$this->payload = $hex .'4e54590'. $algo . $hash;
}else{
// 暗号化の仕方がわからない
throw new Exception ("Error:暗号化に未対応.");
$this->payload = $hex .'4e54598'. $algo . $hash;
}
}
public function send($NEMpubkey,$NEMprikey,$baseurl = 'http://localhost:7890') {
$nem = new TransactionBuilder($this->net);
$nem -> setting($NEMpubkey, $NEMprikey, $baseurl);
$nem->payload = $this->payload;
$nem -> amount = 0;
$nem -> recipient = $this->recipient;
$nem ->EstimateFee();
$tmp = $nem ->SendNEMver1();
$reslt = $nem->analysis($tmp);
$reslt['fee'] = $nem->fee;
if($reslt['status']){
$this->txid = $reslt['txid'];
}
return $reslt;
}
public function Outfile($dir = '/opt/lampp/htdocs/apo/'){
// あらかじめ保存場所$dirを設定
if(!isset($this->txid)){
throw new Exception("There isn't TXID. send may be not success.");
}
$txid = $this->txid;
$date = date("Y-m-d");
preg_match('/.*?([^\/]+?)(\.[^.]+?)$/', $this->filename, $matches);
$dest = $dir . $matches[1] ." -- Apostille TX $txid -- Date $date" .$matches[2];
return copy($this->filename, $dest);
}
public function Check($baseurl = 'http://localhost:7890'){
$filename_original = $this->filename;
$pattern = '/^(.*?)([^\/]+?)\s\-\-\sApostille\sTX\s([0-9abcdefABCDEF]+?)\s\-\-\sDate\s([0-9\-]+?)(\.[^.]+?)$/';
if(!preg_match($pattern, $filename_original, $matches)){
throw new Exception("Error:FilenameがApostilleで使われる形式ではありません。");
}
$dirpass = $matches[1];
$filename = $matches[2];
$txid = $matches[3];
$date = $matches[4];
$ex = $matches[5];
$nem = new TransactionBuilder($this->net);
$txdata = $nem->GetTX($txid);
if(!$txdata){
// 登録されていないか全ノード死亡
return array('status' => FALSE ,'code' => 1);
}
if(preg_match('/^fe4e5459([08])([0-9abcdef])([0-9abcdef]*)/', $txdata['transaction']['message']['payload'], $matches)){
$type = $matches[1];
$hash = $matches[3];
switch ($matches[2]) {
case 1:$this->algo = 'md5';break;
case 2:$this->algo = 'sha1';break;
case 3:$this->algo = 'sha256';break;
case 8:$this->algo = 'sha3-256';break;
case 9:$this->algo = 'sha3-512';break;
default:return array('status' => FALSE ,'code' => 3);
}
}else{
// messageが正規でない
return array('status' => FALSE ,'code' => 2);
}
$this->Run();
if($this->payload === $txdata['transaction']['message']['payload']){
return array('status' => true ,'code' => 0,'detail' => $txdata['transaction']);
}
}
public function analysis($reslt){
if(isset($reslt['message']) AND $reslt['message'] === 'SUCCESS'){
return array('status' => TRUE, 'txid' => $reslt['transactionHash']['data']);
}else{
return array('status' => FALSE, 'message' => $reslt['message'] );
}
}
}
class common{
public static function getGET($name){
$ret = filter_input(INPUT_GET, $name);
if (isset($ret)){
$ret =str_replace("\0", "", $ret);//Nullバイト攻撃対策
return htmlspecialchars($ret, ENT_QUOTES, 'UTF-8');
}
return '';
}
public static function getPost($name){
$ret = filter_input(INPUT_POST, $name);
if (isset($ret)){
$ret =str_replace("\0", "", $ret);//Nullバイト攻撃対策
return htmlspecialchars($ret, ENT_QUOTES, 'UTF-8');
}
return '';
}
public static function getCookie($name){
$ret = filter_input(INPUT_COOKIE, $name);
if (isset($ret)){
$ret =str_replace("\0", "", $ret);//Nullバイト攻撃対策
return htmlspecialchars($ret, ENT_QUOTES, 'UTF-8');
}
return '';
}
public static function getRequest($name){
$ret = filter_input(INPUT_REQUEST, $name);
if (isset($ret)){
$ret =str_replace("\0", "", $ret);//Nullバイト攻撃対策
return htmlspecialchars($ret, ENT_QUOTES, 'UTF-8');
}
return '';
}
public static function FileDisass($file){
// filepassを分解、/pass/to/file.png を
// 1=/pass/to/ ,2=file ,3=.png
if(preg_match('/^(.*?)([^\/]+?)(\.[^.]+?)$/', $file, $matches)){
return $matches;
}else{
return false;
}
}
}
class History {
// 履歴を取得
public $version_ver1;
public $version_ver2;
public $net;
public $pubkey;
public $prikey;
public $baseurl;
public $pageid = NULL;
public function __construct($net = 'mainnet') {
if($net === 'mainnet'){
$this->version_ver1 = 1744830465;
$this->version_ver2 = 1744830466;
}elseif($net === 'testnet'){
$this->version_ver1 = -1744830463;
$this->version_ver2 = -1744830462;
}else{
throw new Exception("Error:net parameter isn't set ,net is mainnet or testnet.");
}
$this->net = $net;
}
public function setting($NEMpubkey,$NEMprikey = null,$baseurl = 'http://localhost:7890'){
$this->pubkey = $NEMpubkey;
$this->address = TransactionBuilder::PubKey2Addr($NEMpubkey, $baseurl);
$this->prikey = $NEMprikey;
$this->baseurl = $baseurl;
}
private function checkWDM(){
if(!isset($this->prikey)){
throw new Exception('Error:$prikey is not set.');
}
// ローカルでのみ使用可能
//if(preg_match('/[localhost|127\.0\.0\.1]/',$this->baseurl) !== 1){
// throw new Exception('Error:It function work only on localhost.');
//}
}
public function IncomingWDM(){
/* Transaction data with decoded messages
* 暗号化されたmessageを復号化して
*/
$this->checkWDM();
$url = $this->baseurl .'/local/account/transfers/incoming';
$POST_DATA = array( 'value' => $this->prikey );
if(isset($this->pageid)){
$POST_DATA['id'] = $this->pageid;
} // 2ページよりidによりページを指示
$history = get_POSTdata($url, json_encode($POST_DATA) );
if(!empty($history['data'])){
$this->pageid = $history['data'][count($history['data']) -1]['meta']['id'];
return $history['data'];
}else{
return FALSE;
}
}
public function OutgoingWDM(){
/* Transaction data with decoded messages
* 暗号化されたmessageを復号化して
*/
$this->checkWDM();
$url = $this->baseurl .'/local/account/transfers/outgoing';
$POST_DATA = array( 'value' => $this->prikey );
if(isset($this->pageid)){
$POST_DATA['id'] = $this->pageid;
} // 2ページよりidによりページを指示
$history = get_POSTdata($url, json_encode($POST_DATA) );
if(!empty($history['data'])){
$this->pageid = $history['data'][count($history['data']) -1]['meta']['id'];
return $history['data'];
}else{
return FALSE;
}
}
public function AllWDM(){
/* Transaction data with decoded messages
* 暗号化されたmessageを復号化して
*/
$this->checkWDM();
$url = $this->baseurl .'/local/account/transfers/all';
$POST_DATA = array( 'value' => $this->prikey );
if(isset($this->pageid)){
$POST_DATA['id'] = $this->pageid;
} // 2ページよりidによりページを指示
$history = get_POSTdata($url, json_encode($POST_DATA) );
if(!empty($history['data'])){
$this->pageid = $history['data'][count($history['data']) -1]['meta']['id'];
return $history['data'];
}else{
return FALSE;
}
}
private function check(){
if(!isset($this->address)){
throw new Exception('Error:$address is not set.');
}
}
public function Incoming(){
/* 通常のHistory取得
*/
$this->check();
$url = $this->baseurl .'/account/transfers/incoming?address=' .$this->address;
if(isset($this->pageid)){
$url .= '&id=' .$this->pageid;
} // 2ページよりidによりページを指示
$history = get_json_array($url);
if(!empty($history['data'])){
$this->pageid = $history['data'][count($history['data']) -1]['meta']['id'];
return $history['data'];
}else{
return FALSE;
}
}
public function Outgoing(){
/* 通常のHistory取得
*/
$this->check();
$url = $this->baseurl .'/account/transfers/outgoing?address=' .$this->address;
if(isset($this->pageid)){
$url .= '&id=' .$this->pageid;
} // 2ページよりidによりページを指示
$history = get_json_array($url);
if(!empty($history['data'])){
$this->pageid = $history['data'][count($history['data']) -1]['meta']['id'];
return $history['data'];
}else{
return FALSE;
}
}
public function All(){
/* 通常のHistory取得
*/
$this->check();
$url = $this->baseurl .'/account/transfers/all?address=' .$this->address;
if(isset($this->pageid)){
$url .= '&id=' .$this->pageid;
} // 2ページよりidによりページを指示
$history = get_json_array($url);
if(!empty($history['data'])){
$this->pageid = $history['data'][count($history['data']) -1]['meta']['id'];
return $history['data'];
}else{
return FALSE;
}
}
public function DecodeArray($transaction){
if(!isset($transaction[0])){
throw new Exception('Error:$transaction key is not numeristic.');
}
$reslt = array();
foreach ($transaction as $transactionValue) {
$tmp = array();
$tmp['height'] = $transactionValue['meta']['height'];
$tmp['timeStamp'] = $transactionValue['transaction']['timeStamp'] + 1427587585;
// 内部ハッシュが実際の送金内容
if(!empty($transactionValue['meta']['innerHash'])){
// Multisig
$tmp['hash'] = $transactionValue['meta']['innerHash']['data'];
$tmp['Multisig'] = TRUE;
$tx_tmp = $transactionValue['transaction']['otherTrans'];
}else{
// No Multisig
$tmp['hash'] = $transactionValue['meta']['hash']['data'];
$tmp['Multisig'] = FALSE;
$tx_tmp = $transactionValue['transaction'];
}
$tmp['siger'] = $tx_tmp['signer'];
$tmp['fee'] = $tx_tmp['fee'];
if($tx_tmp['type'] === 257 AND $tx_tmp['version'] === $this->version_ver1){
// XEM送金トランサクション
$tmp['txtype'] = 1;
$tmp['amount'] = $tx_tmp['amount'];
$tmp['recipient'] = $tx_tmp['recipient'];
$tmp['message'] = $tx_tmp['message'];
}elseif($tx_tmp['type'] === 257 AND $tx_tmp['version'] === $this->version_ver2){
// Mosaic送金トランザクション
$tmp['txtype'] = 2;