-
Notifications
You must be signed in to change notification settings - Fork 6
/
diamond.go
executable file
·1534 lines (1395 loc) · 44.5 KB
/
diamond.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
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
package actions
import (
"bytes"
"encoding/binary"
"encoding/hex"
"fmt"
"github.com/hacash/core/fields"
"github.com/hacash/core/interfaces"
"github.com/hacash/core/interfacev2"
"github.com/hacash/core/stores"
"github.com/hacash/core/sys"
"github.com/hacash/x16rs"
"strings"
)
/**
* diamond tx type
*/
// Start with the 20001st diamond and enable the 32-bit MSG byte
const DiamondCreateCustomMessageAboveNumber uint32 = 20000
// Starting from the 30001st diamond, destroy 90% of the bidding cost
const DiamondCreateBurning90PercentTxFeesAboveNumber uint32 = 30000
// The average bidding cost of 30001 ~ 40000 diamonds is adopted, and the previous setting is 10 diamonds
const DiamondStatisticsAverageBiddingBurningPriceAboveNumber uint32 = 40000
// 40001 diamond, start with Sha3_ Hash (diamondreshash + blockhash) determines diamond shape and color matching
const DiamondResourceHashAndContainBlockHashDecideVisualGeneAboveNumber uint32 = 40000
// 41001 diamond, start with Sha3_ Hash (diamondreshash + blockhash + bidfee) includes the bidding fee to participate in the decision of diamond shape color matching
const DiamondResourceAppendBiddingFeeDecideVisualGeneAboveNumber uint32 = 41000
// Dig out diamonds
type Action_4_DiamondCreate struct {
Diamond fields.DiamondName // Diamond literal wtyuiahxvmekbszn
Number fields.DiamondNumber // Diamond serial number for difficulty check
PrevHash fields.Hash // Previous block hash containing diamond
Nonce fields.Bytes8 // random number
Address fields.Address // Account
// Customer message
CustomMessage fields.Bytes32
// Transaction
belong_trs interfacev2.Transaction
belong_trs_v3 interfaces.Transaction
}
func (elm *Action_4_DiamondCreate) Kind() uint16 {
return 4
}
// json api
func (elm *Action_4_DiamondCreate) Describe() map[string]interface{} {
var data = map[string]interface{}{}
return data
}
func (elm *Action_4_DiamondCreate) Size() uint32 {
size := 2 +
elm.Diamond.Size() +
elm.Number.Size() +
elm.PrevHash.Size() +
elm.Nonce.Size() +
elm.Address.Size()
// Add MSG byte
if uint32(elm.Number) > DiamondCreateCustomMessageAboveNumber {
size += elm.CustomMessage.Size()
}
return size
}
func (elm *Action_4_DiamondCreate) GetRealCustomMessage() []byte {
if uint32(elm.Number) > DiamondCreateCustomMessageAboveNumber {
var msgBytes, _ = elm.CustomMessage.Serialize()
return msgBytes
}
return []byte{}
}
func (elm *Action_4_DiamondCreate) Serialize() ([]byte, error) {
var kindByte = make([]byte, 2)
binary.BigEndian.PutUint16(kindByte, elm.Kind())
var diamondBytes, _ = elm.Diamond.Serialize()
var numberBytes, _ = elm.Number.Serialize()
var prevBytes, _ = elm.PrevHash.Serialize()
var nonceBytes, _ = elm.Nonce.Serialize()
var addrBytes, _ = elm.Address.Serialize()
var buffer bytes.Buffer
buffer.Write(kindByte)
buffer.Write(diamondBytes)
buffer.Write(numberBytes)
buffer.Write(prevBytes)
buffer.Write(nonceBytes)
buffer.Write(addrBytes)
// Add MSG byte
if uint32(elm.Number) > DiamondCreateCustomMessageAboveNumber {
var msgBytes, _ = elm.CustomMessage.Serialize()
buffer.Write(msgBytes)
}
return buffer.Bytes(), nil
}
func (elm *Action_4_DiamondCreate) Parse(buf []byte, seek uint32) (uint32, error) {
var e error = nil
moveseek1, e := elm.Diamond.Parse(buf, seek)
if e != nil {
return 0, e
}
moveseek2, e := elm.Number.Parse(buf, moveseek1)
if e != nil {
return 0, e
}
moveseek3, e := elm.PrevHash.Parse(buf, moveseek2)
if e != nil {
return 0, e
}
moveseek4, e := elm.Nonce.Parse(buf, moveseek3)
if e != nil {
return 0, e
}
moveseek5, e := elm.Address.Parse(buf, moveseek4)
if e != nil {
return 0, e
}
// Add MSG byte
if uint32(elm.Number) > DiamondCreateCustomMessageAboveNumber {
moveseek5, e = elm.CustomMessage.Parse(buf, moveseek5)
if e != nil {
return 0, e
}
}
return moveseek5, nil
}
func (elm *Action_4_DiamondCreate) RequestSignAddresses() []fields.Address {
return []fields.Address{} // no sign
}
//var test_dia_bid_burning float64 = 0.0
func (act *Action_4_DiamondCreate) WriteInChainState(state interfaces.ChainStateOperation) error {
if act.belong_trs_v3 == nil {
panic("Action belong to transaction not be nil !")
}
/* // test get burning
pdhei := state.GetPendingBlockHeight()
if pdhei > 408170 {
test_dia_bid_burning += act.belong_trs_v3.GetFee().ToMei()
if pdhei % 1000 == 0 || pdhei > 509700 {
fmt.Println("- - - - dia_bid_burning:", test_dia_bid_burning)
}
}
*/
blockstore := state.BlockStore()
//区块高度
pending := state.GetPending()
blkhei := state.GetPendingBlockHeight()
blkhash := state.GetPendingBlockHash()
diamondVisualUseContainBlockHash := blkhash
if diamondVisualUseContainBlockHash == nil || len(diamondVisualUseContainBlockHash) != 32 {
diamondVisualUseContainBlockHash = bytes.Repeat([]byte{0}, 32)
}
// Whether comprehensive inspection is necessary
var mustDoAllCheck = true
lateststatus, e := state.LatestStatusRead()
if e != nil {
return e
}
if sys.TestDebugLocalDevelopmentMark {
mustDoAllCheck = false // Developer mode does not check
}
//fmt.Println(state.IsDatabaseVersionRebuildMode(), "-------------------------")
if state.IsDatabaseVersionRebuildMode() {
mustDoAllCheck = false // Database upgrade mode does not check
}
// Calculate diamond hash
sha3hash, diamondResHash, diamondStr := x16rs.Diamond(uint32(act.Number), act.PrevHash, act.Nonce, act.Address, act.GetRealCustomMessage())
// Whether to conduct comprehensive inspection
if mustDoAllCheck {
// Transaction can only contain one and only one action
belongactionnum := len(act.belong_trs_v3.GetActionList())
if 1 != belongactionnum {
return fmt.Errorf("Diamond create tx need only one action but got %d actions.", belongactionnum)
}
// Check block height
// Check whether the block height value is a multiple of 5
// {backtopool} means to throw it back to the trading pool and wait for the next block to be processed again
if blkhei%5 != 0 {
return fmt.Errorf("{BACKTOPOOL} Diamond must be in block height multiple of 5.")
}
// Miner status inspection
lastdiamond := lateststatus.ReadLastestDiamond()
if lastdiamond == nil && act.Number > 1 {
// Not the first diamond but can not read the information of the last diamond
return fmt.Errorf("Cannot ReadLastestDiamond() to get last diamond of act.Number > 1.")
}
if lastdiamond != nil {
//fmt.Println(lastdiamond.Diamond)
//fmt.Println(lastdiamond.Number)
//fmt.Println(lastdiamond.ContainBlockHash.ToHex())
//fmt.Println(lastdiamond.PrevContainBlockHash.ToHex())
prevdiamondnum, prevdiamondhash := uint32(lastdiamond.Number), lastdiamond.ContainBlockHash
if prevdiamondhash == nil {
return fmt.Errorf("lastdiamond.ContainBlockHash is nil.")
}
// Check if the diamond is from the previous block
if act.PrevHash.Equal(prevdiamondhash) != true {
return fmt.Errorf("Diamond prev hash must be <%s> but got <%s>.", hex.EncodeToString(prevdiamondhash), hex.EncodeToString(act.PrevHash))
}
if prevdiamondnum+1 != uint32(act.Number) {
return fmt.Errorf("Diamond number must be <%d> but got <%d>.", prevdiamondnum+1, act.Number)
}
}
// Check diamond mining calculation
diamondstrval, isdia := x16rs.IsDiamondHashResultString(diamondStr)
if !isdia {
return fmt.Errorf("String <%s> is not diamond.", diamondStr)
}
if strings.Compare(diamondstrval, string(act.Diamond)) != 0 {
return fmt.Errorf("Diamond need <%s> but got <%s>", act.Diamond, diamondstrval)
}
// Check diamond difficulty value
difok := x16rs.CheckDiamondDifficulty(uint32(act.Number), sha3hash, diamondResHash)
if !difok {
return fmt.Errorf("block %d Diamond difficulty not meet the requirements.", blkhei)
}
// Query whether the diamond already exists
hasaddr, e := state.Diamond(act.Diamond)
if e != nil {
return e
}
if hasaddr != nil {
return fmt.Errorf("Diamond <%s> already exist.", string(act.Diamond))
}
// Check that a block can contain only one diamond
pendingdiamond := pending.GetWaitingSubmitDiamond()
if pendingdiamond != nil {
return fmt.Errorf("This block height:%d has already exist diamond:<%s> .", blkhei, pendingdiamond.Diamond)
}
// All conditions checked successfully
}
// Deposit diamonds
//fmt.Println(act.Address.ToReadable())
var diastore = stores.NewDiamond(act.Address)
diastore.Address = act.Address // Diamond address
e3 := state.DiamondSet(act.Diamond, diastore)
if e3 != nil {
return e3
}
// Increase diamond balance +1
e9 := DoAddDiamondFromChainStateV3(state, act.Address, 1)
if e9 != nil {
return e9
}
// Set miner status
// Mark that this block already contains diamonds
// Storing objects, computing visual genes
lifeGene, e15 := calculateLifeGeneByDiamondStuffHashV3(act.belong_trs_v3, uint32(act.Number), diamondResHash, diamondStr, diamondVisualUseContainBlockHash)
if e15 != nil {
return e15
}
var diamondstore = &stores.DiamondSmelt{
Diamond: act.Diamond,
Number: act.Number,
ContainBlockHeight: fields.BlockHeight(blkhei),
ContainBlockHash: state.GetPendingBlockHash(),
PrevContainBlockHash: act.PrevHash,
MinerAddress: act.Address,
Nonce: act.Nonce,
CustomMessage: act.GetRealCustomMessage(),
LifeGene: lifeGene,
}
// Write service charge quotation
feeoffer := act.belong_trs_v3.GetFee()
e11 := diamondstore.ParseApproxFeeOffer(feeoffer)
if e11 != nil {
return e11
}
// Total supply statistics
totalsupply, e2 := state.ReadTotalSupply()
if e2 != nil {
return e2
}
if uint32(act.Number) > DiamondCreateBurning90PercentTxFeesAboveNumber {
// 90% of the cost of destroying this transaction from the 30001 diamond
txfee := act.belong_trs_v3.GetFee().Copy()
if txfee.Unit < 2 {
return fmt.Errorf("Tx fee %s to low", txfee)
}
txf2 := act.belong_trs_v3.GetFee().Copy()
txf2.Unit -= 1
txfee, e = txfee.Sub(txf2)
if e != nil {
return fmt.Errorf("DiamondBidBurningZhu sub 90%% error: %s", e)
}
var txfeezhu = txfee.ToZhuOmit()
totalsupply.DoAddUint(stores.TotalSupplyStoreTypeOfDiamondBidBurningZhu, txfeezhu)
}
// Calculate the average number of HACs for bidding
if uint32(act.Number) <= DiamondStatisticsAverageBiddingBurningPriceAboveNumber {
diamondstore.AverageBidBurnPrice = 10 // Fixed to 10
} else {
bsnum := uint32(act.Number) - DiamondCreateBurning90PercentTxFeesAboveNumber
burnhaczhu := totalsupply.GetUint(stores.TotalSupplyStoreTypeOfDiamondBidBurningZhu)
bidprice := burnhaczhu/100000000/uint64(bsnum) + 1 // up to 1
diamondstore.AverageBidBurnPrice = fields.VarUint2(uint16(bidprice)) // min 1
}
// Update block status
lateststatus.SetLastestDiamond(diamondstore)
pending.SetWaitingSubmitDiamond(diamondstore)
// Save status
e = state.LatestStatusSet(lateststatus)
if e != nil {
return e
}
// Save diamonds
if state.IsInTxPool() == false {
e = blockstore.SaveDiamond(diamondstore)
if e != nil {
return e
}
e = blockstore.UpdateSetDiamondNameReferToNumber(uint32(diamondstore.Number), diamondstore.Diamond)
if e != nil {
return e
}
}
totalsupply.SetUint(stores.TotalSupplyStoreTypeOfDiamond, uint64(act.Number))
// update total supply
e7 := state.UpdateSetTotalSupply(totalsupply)
if e7 != nil {
return e7
}
// update
//e = state.LatestStatusSet(lateststatus)
//if e != nil {
// return e
//}
e = state.SetPending(pending)
if e != nil {
return e
}
//fmt.Println("Action_4_DiamondCreate:", diamondstore.Number, string(diamondstore.Diamond), diamondstore.MinerAddress.ToReadable())
//fmt.Print(string(diamondstore.Diamond)+",")
//fmt.Println("Action_4_DiamondCreate:", act.Nonce)
return nil
}
func (act *Action_4_DiamondCreate) WriteinChainState(state interfacev2.ChainStateOperation) error {
panic("WriteinChainState be deprecated")
if act.belong_trs == nil {
panic("Action belong to transaction not be nil !")
}
//区块高度
blkhei := state.GetPendingBlockHeight()
blkhash := state.GetPendingBlockHash()
diamondVisualUseContainBlockHash := blkhash
if diamondVisualUseContainBlockHash == nil || len(diamondVisualUseContainBlockHash) != 32 {
diamondVisualUseContainBlockHash = bytes.Repeat([]byte{0}, 32)
}
// Whether comprehensive inspection is necessary
var mustDoAllCheck = true
if sys.TestDebugLocalDevelopmentMark {
mustDoAllCheck = false // Developer mode does not check
}
//fmt.Println(state.IsDatabaseVersionRebuildMode(), "-------------------------")
if state.IsDatabaseVersionRebuildMode() {
mustDoAllCheck = false // Database upgrade mode does not check
}
// Calculate diamond hash
sha3hash, diamondResHash, diamondStr := x16rs.Diamond(uint32(act.Number), act.PrevHash, act.Nonce, act.Address, act.GetRealCustomMessage())
// Whether to conduct comprehensive inspection
if mustDoAllCheck {
// Transaction can only contain one and only one action
belongactionnum := len(act.belong_trs.GetActions())
if 1 != belongactionnum {
return fmt.Errorf("Diamond create tx need only one action but got %d actions.", belongactionnum)
}
// Check block height
// Check whether the block height value is a multiple of 5
// {backtopool} means to throw it back to the trading pool and wait for the next block to be processed again
if blkhei%5 != 0 {
return fmt.Errorf("{BACKTOPOOL} Diamond must be in block height multiple of 5.")
}
// Miner status inspection
lastdiamond, err := state.ReadLastestDiamond()
if err != nil {
return err
}
if lastdiamond == nil && act.Number > 1 {
// Not the first diamond but can not read the information of the last diamond
return fmt.Errorf("Cannot ReadLastestDiamond() to get last diamond of act.Number > 1.")
}
if lastdiamond != nil {
//fmt.Println(lastdiamond.Diamond)
//fmt.Println(lastdiamond.Number)
//fmt.Println(lastdiamond.ContainBlockHash.ToHex())
//fmt.Println(lastdiamond.PrevContainBlockHash.ToHex())
prevdiamondnum, prevdiamondhash := uint32(lastdiamond.Number), lastdiamond.ContainBlockHash
if prevdiamondhash == nil {
return fmt.Errorf("lastdiamond.ContainBlockHash is nil.")
}
// Check if the diamond is from the previous block
if act.PrevHash.Equal(prevdiamondhash) != true {
return fmt.Errorf("Diamond prev hash must be <%s> but got <%s>.", hex.EncodeToString(prevdiamondhash), hex.EncodeToString(act.PrevHash))
}
if prevdiamondnum+1 != uint32(act.Number) {
return fmt.Errorf("Diamond number must be <%d> but got <%d>.", prevdiamondnum+1, act.Number)
}
}
// Check diamond mining calculation
diamondstrval, isdia := x16rs.IsDiamondHashResultString(diamondStr)
if !isdia {
return fmt.Errorf("String <%s> is not diamond.", diamondStr)
}
if strings.Compare(diamondstrval, string(act.Diamond)) != 0 {
return fmt.Errorf("Diamond need <%s> but got <%s>", act.Diamond, diamondstrval)
}
// Check diamond difficulty value
difok := x16rs.CheckDiamondDifficulty(uint32(act.Number), sha3hash, diamondResHash)
if !difok {
return fmt.Errorf("Diamond difficulty not meet the requirements.")
}
// Query whether the diamond already exists
hasaddr, e := state.Diamond(act.Diamond)
if e != nil {
return e
}
if hasaddr != nil {
return fmt.Errorf("Diamond <%s> already exist.", string(act.Diamond))
}
// Check that a block can contain only one diamond
pendingdiamond, e2 := state.GetPendingSubmitStoreDiamond()
if e2 != nil {
return e2
}
if pendingdiamond != nil {
return fmt.Errorf("This block height:%d has already exist diamond:<%s> .", blkhei, pendingdiamond.Diamond)
}
// All conditions checked successfully
}
// Deposit diamonds
//fmt.Println(act.Address.ToReadable())
var diastore = stores.NewDiamond(act.Address)
diastore.Address = act.Address // Diamond address
e3 := state.DiamondSet(act.Diamond, diastore)
if e3 != nil {
return e3
}
// Increase diamond balance +1
e9 := DoAddDiamondFromChainState(state, act.Address, 1)
if e9 != nil {
return e9
}
// Set miner status
// Mark that this block already contains diamonds
// Storing objects, computing visual genes
lifeGene, e15 := calculateLifeGeneByDiamondStuffHash(act.belong_trs, uint32(act.Number), diamondResHash, diamondStr, diamondVisualUseContainBlockHash)
if e15 != nil {
return e15
}
var diamondstore = &stores.DiamondSmelt{
Diamond: act.Diamond,
Number: act.Number,
ContainBlockHeight: fields.BlockHeight(blkhei),
ContainBlockHash: blkhash,
PrevContainBlockHash: act.PrevHash,
MinerAddress: act.Address,
Nonce: act.Nonce,
CustomMessage: act.GetRealCustomMessage(),
LifeGene: lifeGene,
}
// Write service charge quotation
feeoffer := act.belong_trs.GetFee()
e11 := diamondstore.ParseApproxFeeOffer(feeoffer)
if e11 != nil {
return e11
}
// Total supply statistics
totalsupply, e2 := state.ReadTotalSupply()
if e2 != nil {
return e2
}
// Calculate the average number of HACs for bidding
if uint32(act.Number) <= DiamondStatisticsAverageBiddingBurningPriceAboveNumber {
diamondstore.AverageBidBurnPrice = 10 // Fixed to 10
} else {
bsnum := uint32(act.Number) - DiamondCreateBurning90PercentTxFeesAboveNumber
burnhac := totalsupply.Get(stores.TotalSupplyStoreTypeOfBurningTotal)
bidprice := uint64(burnhac/float64(bsnum) + 0.99999999) // up 1
setprice := fields.VarUint2(bidprice)
if setprice < 1 {
setprice = 1 // Minimum 1
}
diamondstore.AverageBidBurnPrice = setprice
}
// Set latest status
e4 := state.SetLastestDiamond(diamondstore)
if e4 != nil {
return e4
}
e5 := state.SetPendingSubmitStoreDiamond(diamondstore)
if e5 != nil {
return e5
}
totalsupply.SetUint(stores.TotalSupplyStoreTypeOfDiamond, uint64(act.Number))
// update total supply
e7 := state.UpdateSetTotalSupply(totalsupply)
if e7 != nil {
return e7
}
//fmt.Println("Action_4_DiamondCreate:", diamondstore.Number, string(diamondstore.Diamond), diamondstore.MinerAddress.ToReadable())
//fmt.Print(string(diamondstore.Diamond)+",")
//fmt.Println("Action_4_DiamondCreate:", act.Nonce)
return nil
}
func (act *Action_4_DiamondCreate) RecoverChainState(state interfacev2.ChainStateOperation) error {
panic("RecoverChainState be deprecated")
//chainstate := state.BlockStore()
//if chainstate == nil {
// panic("Action get state.Miner() cannot be nil !")
//}
// Delete diamond
e1 := state.DiamondDel(act.Diamond)
if e1 != nil {
return e1
}
// Fallback miner status
chainstore := state.BlockStore()
if chainstore == nil {
return fmt.Errorf("not find BlockStore object.")
}
prevDiamond, e2 := chainstore.ReadDiamondByNumber(uint32(act.Number) - 1)
if e2 != nil {
return e1
}
// setPrev
e3 := state.SetLastestDiamond(prevDiamond)
if e3 != nil {
return e3
}
// Deduct diamond balance -1
e9 := DoSubDiamondFromChainState(state, act.Address, 1)
if e9 != nil {
return e9
}
// Total supply statistics
totalsupply, e2 := state.ReadTotalSupply()
if e2 != nil {
return e2
}
totalsupply.SetUint(stores.TotalSupplyStoreTypeOfDiamond, uint64(uint32(act.Number)-1))
// update total supply
e7 := state.UpdateSetTotalSupply(totalsupply)
if e7 != nil {
return e7
}
return nil
}
func (elm *Action_4_DiamondCreate) SetBelongTransaction(t interfacev2.Transaction) {
panic("SetBelongTransaction be deprecated")
elm.belong_trs = t
}
func (elm *Action_4_DiamondCreate) SetBelongTrs(t interfaces.Transaction) {
elm.belong_trs_v3 = t
}
// burning fees // IsBurning 90 PersentTxFees
func (act *Action_4_DiamondCreate) IsBurning90PersentTxFees() bool {
if uint32(act.Number) > DiamondCreateBurning90PercentTxFeesAboveNumber {
// 90% of the cost of destroying this transaction from the 30001 diamond
return true
}
return false
}
///////////////////////////////////////////////////////////////
// Calculate the visual gene of diamond
func calculateLifeGeneByDiamondStuffHash(belong_trs interfacev2.Transaction, number uint32, stuffhx []byte, diamondstr string, peddingblkhash []byte) (fields.Hash, error) {
if len(stuffhx) != 32 || len(peddingblkhash) != 32 {
return nil, fmt.Errorf("stuffhx and peddingblkhash length must 32")
}
if len(diamondstr) != 16 {
return nil, fmt.Errorf("diamondstr length must 16")
}
vgenehash := make([]byte, 32)
copy(vgenehash, stuffhx)
if number > DiamondResourceHashAndContainBlockHashDecideVisualGeneAboveNumber {
// 40001 diamond, start with Sha3_ Hash (diamondreshash, blockhash) determines diamond shape and color matching
vgenestuff := bytes.NewBuffer(stuffhx)
vgenestuff.Write(peddingblkhash)
if number > DiamondResourceAppendBiddingFeeDecideVisualGeneAboveNumber {
bidfeebts, e := belong_trs.GetFee().Serialize() // bid fee
if e != nil {
return nil, e // Return error
}
vgenestuff.Write(bidfeebts) // Bidding fee participates in determining diamond shape and color matching
}
vgenehash = fields.CalculateHash(vgenestuff.Bytes()) // Open blind box
// Like block hash, it is random, and the shape and color matching can only be known when the diamond is confirmed
// fmt.Println(hex.EncodeToString(vgenestuff.Bytes()))
}
// fmt.Printf("Calculate Visual Gene #%d, vgenehash: %s, stuffhx: %s, peddingblkhash: %s\n", number, hex.EncodeToString(vgenehash), hex.EncodeToString(stuffhx), hex.EncodeToString(peddingblkhash))
return vgenehash, nil
/*
genehexstr := make([]string, 18)
// Top 6
k := 0
for i := 10; i < 16; i++ {
s := diamondstr[i]
e := "0"
switch s {
case 'W': // WTYUIAHXVMEKBSZN
e = "0"
case 'T':
e = "1"
case 'Y':
e = "2"
case 'U':
e = "3"
case 'I':
e = "4"
case 'A':
e = "5"
case 'H':
e = "6"
case 'X':
e = "7"
case 'V':
e = "8"
case 'M':
e = "9"
case 'E':
e = "A"
case 'K':
e = "B"
case 'B':
e = "C"
case 'S':
e = "D"
case 'Z':
e = "E"
case 'N':
e = "F"
}
genehexstr[k] = e
k++
}
// Last 11 digits
for i := 20; i < 31; i++ {
x := vgenehash[i]
x = x % 16
e := "0"
switch x {
case 0:
e = "0"
case 1:
e = "1"
case 2:
e = "2"
case 3:
e = "3"
case 4:
e = "4"
case 5:
e = "5"
case 6:
e = "6"
case 7:
e = "7"
case 8:
e = "8"
case 9:
e = "9"
case 10:
e = "A"
case 11:
e = "B"
case 12:
e = "C"
case 13:
e = "D"
case 14:
e = "E"
case 15:
e = "F"
}
genehexstr[k] = e
k++
}
// Make up the last digit
genehexstr[17] = "0"
resbts, e1 := hex.DecodeString(strings.Join(genehexstr, ""))
if e1 != nil {
return nil, e1
}
// Last bit of hash as shape selection
resbuf := bytes.NewBuffer([]byte{vgenehash[31]})
resbuf.Write(resbts) // Color selector
return resbuf.Bytes(), nil
*/
}
// Calculate the visual gene of diamond
func calculateLifeGeneByDiamondStuffHashV3(belong_trs interfaces.Transaction, number uint32, stuffhx []byte, diamondstr string, peddingblkhash []byte) (fields.Hash, error) {
if len(stuffhx) != 32 || len(peddingblkhash) != 32 {
return nil, fmt.Errorf("stuffhx and peddingblkhash length must 32")
}
if len(diamondstr) != 16 {
return nil, fmt.Errorf("diamondstr length must 16")
}
vgenehash := make([]byte, 32)
copy(vgenehash, stuffhx)
if number > DiamondResourceHashAndContainBlockHashDecideVisualGeneAboveNumber {
// 40001 diamond, start with Sha3_ Hash (diamondreshash, blockhash) determines diamond shape and color matching
vgenestuff := bytes.NewBuffer(stuffhx)
vgenestuff.Write(peddingblkhash)
if number > DiamondResourceAppendBiddingFeeDecideVisualGeneAboveNumber {
bidfeebts, e := belong_trs.GetFee().Serialize() // bid fee
if e != nil {
return nil, e // Return error
}
vgenestuff.Write(bidfeebts) // Bidding fee participates in determining diamond shape and color matching
}
vgenehash = fields.CalculateHash(vgenestuff.Bytes()) // Open blind box
// Like block hash, it is random, and the shape and color matching can only be known when the diamond is confirmed
// fmt.Println(hex.EncodeToString(vgenestuff.Bytes()))
}
return vgenehash, nil
/*
// fmt.Printf("Calculate Visual Gene #%d, vgenehash: %s, stuffhx: %s, peddingblkhash: %s\n", number, hex.EncodeToString(vgenehash), hex.EncodeToString(stuffhx), hex.EncodeToString(peddingblkhash))
genehexstr := make([]string, 18)
// Top 6
k := 0
for i := 10; i < 16; i++ {
s := diamondstr[i]
e := "0"
switch s {
case 'W': // WTYUIAHXVMEKBSZN
e = "0"
case 'T':
e = "1"
case 'Y':
e = "2"
case 'U':
e = "3"
case 'I':
e = "4"
case 'A':
e = "5"
case 'H':
e = "6"
case 'X':
e = "7"
case 'V':
e = "8"
case 'M':
e = "9"
case 'E':
e = "A"
case 'K':
e = "B"
case 'B':
e = "C"
case 'S':
e = "D"
case 'Z':
e = "E"
case 'N':
e = "F"
}
genehexstr[k] = e
k++
}
// Last 11 digits
for i := 20; i < 31; i++ {
x := vgenehash[i]
x = x % 16
e := "0"
switch x {
case 0:
e = "0"
case 1:
e = "1"
case 2:
e = "2"
case 3:
e = "3"
case 4:
e = "4"
case 5:
e = "5"
case 6:
e = "6"
case 7:
e = "7"
case 8:
e = "8"
case 9:
e = "9"
case 10:
e = "A"
case 11:
e = "B"
case 12:
e = "C"
case 13:
e = "D"
case 14:
e = "E"
case 15:
e = "F"
}
genehexstr[k] = e
k++
}
// Make up the last digit
genehexstr[17] = "0"
resbts, e1 := hex.DecodeString(strings.Join(genehexstr, ""))
if e1 != nil {
return nil, e1
}
// Last bit of hash as shape selection
resbuf := bytes.NewBuffer([]byte{vgenehash[31]})
resbuf.Write(resbts) // Color selector
return resbuf.Bytes(), nil
*/
}
///////////////////////////////////////////////////////////////
// Transfer diamond
type Action_5_DiamondTransfer struct {
Diamond fields.DiamondName // Diamond literal wtyuiahxvmekbszn
ToAddress fields.Address // receive address
// Data pointer
// Transaction
belong_trs interfacev2.Transaction
belong_trs_v3 interfaces.Transaction
}
func (elm *Action_5_DiamondTransfer) Kind() uint16 {
return 5
}
// json api
func (elm *Action_5_DiamondTransfer) Describe() map[string]interface{} {
var data = map[string]interface{}{}
return data
}
func (elm *Action_5_DiamondTransfer) Size() uint32 {
return 2 + elm.Diamond.Size() + elm.ToAddress.Size()
}
func (elm *Action_5_DiamondTransfer) Serialize() ([]byte, error) {
var kindByte = make([]byte, 2)
binary.BigEndian.PutUint16(kindByte, elm.Kind())
var diamondBytes, _ = elm.Diamond.Serialize()
var addrBytes, _ = elm.ToAddress.Serialize()
var buffer bytes.Buffer
buffer.Write(kindByte)
buffer.Write(diamondBytes)
buffer.Write(addrBytes)
return buffer.Bytes(), nil
}
func (elm *Action_5_DiamondTransfer) Parse(buf []byte, seek uint32) (uint32, error) {
var moveseek1, _ = elm.Diamond.Parse(buf, seek)
var moveseek2, _ = elm.ToAddress.Parse(buf, moveseek1)
return moveseek2, nil
}
func (elm *Action_5_DiamondTransfer) RequestSignAddresses() []fields.Address {
return []fields.Address{} // not sign
}
func (act *Action_5_DiamondTransfer) WriteInChainState(state interfaces.ChainStateOperation) error {
if act.belong_trs_v3 == nil {
panic("Action belong to transaction not be nil !")
}
trsMainAddress := act.belong_trs_v3.GetAddress()
//fmt.Println("Action_5_DiamondTransfer:", trsMainAddress.ToReadable(), act.Address.ToReadable(), string(act.Diamond))
// cannot trs to self
if bytes.Compare(act.ToAddress, trsMainAddress) == 0 {
return fmt.Errorf("Cannot transfer to self.")
}
// Query whether the diamond already exists
diaitem, e := state.Diamond(act.Diamond)
if e != nil {
return e
}
if diaitem == nil {
return fmt.Errorf("Diamond <%s> not exist.", string(act.Diamond))
}
item := diaitem
// check belong and status
ckerr := CheckDiamondStatusNormalAndBelong(&act.Diamond, diaitem, &trsMainAddress)
if ckerr != nil {
return ckerr
}
// Transfer diamond
item.Address = act.ToAddress
err := state.DiamondSet(act.Diamond, item)
if err != nil {
return err
}
// Transfer diamond balance
e9 := DoSimpleDiamondTransferFromChainStateV3(state, trsMainAddress, act.ToAddress, 1)
if e9 != nil {
return e9
}
return nil
}
func (act *Action_5_DiamondTransfer) WriteinChainState(state interfacev2.ChainStateOperation) error {
if act.belong_trs == nil {
panic("Action belong to transaction not be nil !")
}
trsMainAddress := act.belong_trs.GetAddress()
//fmt.Println("Action_5_DiamondTransfer:", trsMainAddress.ToReadable(), act.Address.ToReadable(), string(act.Diamond))
// cannot trs to self
if bytes.Compare(act.ToAddress, trsMainAddress) == 0 {
return fmt.Errorf("Cannot transfer to self.")
}
// Query whether the diamond already exists
diaitem, e := state.Diamond(act.Diamond)
if e != nil {
return e
}
if diaitem == nil {
return fmt.Errorf("Diamond <%s> not exist.", string(act.Diamond))
}
item := diaitem
// Check whether it is mortgaged and whether it can be transferred
if diaitem.Status != stores.DiamondStatusNormal {
return fmt.Errorf("Diamond <%s> has been mortgaged and cannot be transferred.", string(act.Diamond))
}