This repository was archived by the owner on Mar 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 82
Expand file tree
/
Copy pathblockchain_txn_vars_v1.erl
More file actions
1801 lines (1632 loc) · 68.9 KB
/
Copy pathblockchain_txn_vars_v1.erl
File metadata and controls
1801 lines (1632 loc) · 68.9 KB
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
%%%-------------------------------------------------------------------
%% @doc
%% == Blockchain Transaction Chain Vars ==
%% @end
%%%-------------------------------------------------------------------
-module(blockchain_txn_vars_v1).
-behavior(blockchain_txn).
-behavior(blockchain_json).
-include("blockchain.hrl").
-include("blockchain_json.hrl").
-include("blockchain_txn_fees.hrl").
-include("blockchain_vars.hrl").
-include_lib("helium_proto/include/blockchain_txn_vars_v1_pb.hrl").
-export([
new/2, new/3,
hash/1,
fee/1,
fee_payer/2,
is_valid/2,
master_key/1,
multi_keys/1,
key_proof/1, key_proof/2,
multi_key_proofs/1, multi_key_proofs/2,
proof/1, proof/2,
multi_proofs/1, multi_proofs/2,
vars/1,
to_var/2,
from_var/1,
decoded_vars/1,
version_predicate/1,
unsets/1,
cancels/1,
nonce/1,
absorb/2,
rescue_absorb/2,
sign/2,
print/1,
json_type/0,
to_json/2,
process_hooks/3,
var_hook/3, unset_hook/2
]).
%% helper API
-export([
create_proof/2,
legacy_create_proof/2,
maybe_absorb/3,
delayed_absorb/2
]).
-ifdef(TEST).
-include_lib("stdlib/include/assert.hrl").
-include_lib("eunit/include/eunit.hrl").
-define(exceptions, [garbage_value]).
-define(allowed_predicate_funs, [test_version, version]).
-else.
-define(exceptions, []).
-define(allowed_predicate_funs, [version]).
-endif.
-ifdef(TEST).
-define(min_snap_interval, 1).
-define(expire_lower_bound, 2).
-else.
-define(min_snap_interval, 4*60).
-define(expire_lower_bound, 9).
-endif.
-type txn_vars() :: #blockchain_txn_vars_v1_pb{}.
-export_type([txn_vars/0]).
%% message var_v1 {
%% string name = 1;
%% string type = 2;
%% bytes value = 3;
%% }
%% message txn_vars_v1 {
%% map<string, var> vars = 1;
%% uint32 version_predicate = 2;
%% bytes master_key = 4;
%% bytes key_proof = 5;
%% repeated bytes cancels = 6;
%% repeated bytes unsets = 7;
%% uint32 nonce = 8;
%% repeated bytes multi_keys = 9;
%% repeated bytes multi_proofs = 10;
%% repeated bytes multi_key_proof = 11;
%% }
-spec new(#{}, integer()) -> txn_vars().
new(Vars, Nonce) ->
new(Vars, Nonce, #{}).
-spec new(#{atom() => any()}, integer(), #{atom() => any()}) -> txn_vars().
new(Vars, Nonce, Optional) ->
VersionP = maps:get(version_predicate, Optional, 0),
MasterKey = maps:get(master_key, Optional, <<>>),
MultiKeys = maps:get(multi_keys, Optional, []),
MultiKeyProofs = maps:get(multi_key_proofs, Optional, []),
KeyProof = maps:get(key_proof, Optional, <<>>),
Unsets = maps:get(unsets, Optional, []),
Cancels = maps:get(cancels, Optional, []),
%% note that string inputs are normalized on creation, which has
%% an effect on proof encoding :/
#blockchain_txn_vars_v1_pb{vars = lists:sort(encode_vars(Vars)),
version_predicate = VersionP,
unsets = encode_unsets(Unsets),
cancels = Cancels,
nonce = Nonce,
master_key = MasterKey,
key_proof = KeyProof,
multi_keys = MultiKeys,
multi_key_proofs = MultiKeyProofs}.
encode_vars(Vars) ->
V = maps:to_list(Vars),
lists:map(fun({K, Val}) ->
to_var(atom_to_list(K), Val)
end,V).
encode_unsets(Unsets) ->
lists:map(fun(U) -> atom_to_binary(U, utf8) end, Unsets).
to_var(Name, V) when is_binary(V) ->
#blockchain_var_v1_pb{name = Name, type = "binary", value = V};
to_var(Name, V) when is_list(V) ->
#blockchain_var_v1_pb{name = Name, type = "string", value = iolist_to_binary(V)};
to_var(Name, V) when is_integer(V) ->
#blockchain_var_v1_pb{name = Name, type = "int", value = integer_to_binary(V)};
to_var(Name, V) when is_float(V) ->
#blockchain_var_v1_pb{name = Name, type = "float", value = float_to_binary(V)};
to_var(Name, V) when is_atom(V) ->
#blockchain_var_v1_pb{name = Name, type = "atom", value = atom_to_binary(V, utf8)};
to_var(_Name, _V) ->
lager:warning("bad var: ~p, value ~p", [_Name, _V]),
error(bad_var_type).
decode_vars(PBList) ->
lists:foldl(
fun(V, Acc) ->
{K, V1} = from_var(V),
K1 = list_to_atom(K),
Acc#{K1 => V1}
end,
#{},
PBList).
from_var(#blockchain_var_v1_pb{name = Name, type = "binary", value = V}) ->
{Name, V};
from_var(#blockchain_var_v1_pb{name = Name, type = "string", value = V}) ->
{Name, V};
from_var(#blockchain_var_v1_pb{name = Name, type = "int", value = V}) ->
{Name, binary_to_integer(V)};
from_var(#blockchain_var_v1_pb{name = Name, type = "float", value = V}) ->
{Name, binary_to_float(V)};
from_var(#blockchain_var_v1_pb{name = Name, type = "atom", value = V}) ->
{Name, binary_to_atom(V, utf8)};
from_var(_V) ->
error(bad_var_type).
-spec hash(txn_vars()) -> blockchain_txn:hash().
hash(Txn) ->
Vars = vars(Txn),
Vars1 = lists:sort(Vars),
EncodedTxn = blockchain_txn_vars_v1_pb:encode_msg(Txn#blockchain_txn_vars_v1_pb{vars = Vars1}),
crypto:hash(sha256, EncodedTxn).
-spec sign(txn_vars(), libp2p_crypto:sig_fun()) -> txn_vars().
sign(Txn, _SigFun) ->
Txn.
-spec fee(txn_vars()) -> non_neg_integer().
fee(_Txn) ->
0.
-spec fee_payer(txn_vars(), blockchain_ledger_v1:ledger()) -> libp2p_crypto:pubkey_bin() | undefined.
fee_payer(_Txn, _Ledger) ->
undefined.
master_key(Txn) ->
Txn#blockchain_txn_vars_v1_pb.master_key.
multi_keys(Txn) ->
Txn#blockchain_txn_vars_v1_pb.multi_keys.
key_proof(Txn) ->
Txn#blockchain_txn_vars_v1_pb.key_proof.
key_proof(Txn, Proof) ->
Txn#blockchain_txn_vars_v1_pb{key_proof = Proof}.
multi_key_proofs(Txn) ->
Txn#blockchain_txn_vars_v1_pb.multi_key_proofs.
multi_key_proofs(Txn, Proofs) ->
Txn#blockchain_txn_vars_v1_pb{multi_key_proofs = Proofs}.
proof(Txn) ->
Txn#blockchain_txn_vars_v1_pb.proof.
proof(Txn, Proof) ->
Txn#blockchain_txn_vars_v1_pb{proof = Proof}.
multi_proofs(Txn) ->
Txn#blockchain_txn_vars_v1_pb.multi_proofs.
multi_proofs(Txn, Proofs) ->
Txn#blockchain_txn_vars_v1_pb{multi_proofs = Proofs}.
unset_proofs(Txn) ->
Txn#blockchain_txn_vars_v1_pb{proof = <<>>,
key_proof = <<>>,
multi_proofs = [],
multi_key_proofs = []}.
vars(Txn) ->
Txn#blockchain_txn_vars_v1_pb.vars.
decoded_vars(Txn) ->
decode_vars(Txn#blockchain_txn_vars_v1_pb.vars).
version_predicate(Txn) ->
Txn#blockchain_txn_vars_v1_pb.version_predicate.
unsets(Txn) ->
Txn#blockchain_txn_vars_v1_pb.unsets.
cancels(Txn) ->
Txn#blockchain_txn_vars_v1_pb.cancels.
nonce(Txn) ->
Txn#blockchain_txn_vars_v1_pb.nonce.
-spec is_valid(txn_vars(), blockchain:blockchain()) -> ok | {error, atom()} | {error, {atom(), any()}}.
is_valid(Txn, Chain) ->
Ledger = blockchain:ledger(Chain),
Gen =
case blockchain_ledger_v1:current_height(Ledger) of
{ok, 0} ->
true;
_ ->
false
end,
Vars = decode_vars(vars(Txn)),
Version =
case blockchain:config(?chain_vars_version, Ledger) of
{ok, 2} ->
2;
{error, not_found} when Gen == true ->
%% if this isn't on the ledger, allow the contents of
%% the genesis block to choose the validation type
maps:get(?chain_vars_version, Vars, 1);
_ ->
1
end,
case Version of
2 ->
Artifact = create_artifact(Txn),
lager:debug("validating vars ~p artifact ~p", [Vars, Artifact]),
try
Nonce = nonce(Txn),
case blockchain_ledger_v1:vars_nonce(Ledger) of
{ok, LedgerNonce} when Nonce == (LedgerNonce + 1) ->
ok;
{error, not_found} when Gen == true ->
ok;
{error, not_found} ->
throw({error, missing_ledger_nonce});
{ok, LedgerNonce} ->
throw({error, bad_nonce, {exp, (LedgerNonce + 1), {got, Nonce}}})
end,
case Gen of
true -> ok; %% genesis block doesn't validate vars
_ ->
%% do these before the proof, so we can check validation on unsigned txns
%% NB: validation errors MUST throw
maps:map(fun validate_var/2, Vars)
end,
lists:foreach(
fun(VarName) ->
case blockchain:config(VarName, Ledger) of % ignore this one using "?"
{ok, _} -> ok;
{error, not_found} -> throw({error, {unset_var_not_set, VarName}})
end
end,
decode_unsets(unsets(Txn))),
%% here we can accept a valid master key
ok = validate_master_keys(Txn, Gen, Artifact, Ledger),
case Gen of
true ->
%% genesis block requires master key and has already
%% validated the proof if it has made it here.
ok;
_ ->
case blockchain:config(?use_multi_keys, Ledger) of
{ok, true} ->
%% handle the case where this gets set before
%% the keys are set
case blockchain_ledger_v1:multi_keys(Ledger) of
{ok, MultiKeys} ->
MaxProofs = length(MultiKeys),
Proofs = multi_proofs(Txn),
case length(Proofs) > MaxProofs of
true -> throw({error, too_many_proofs});
false ->
case blockchain_utils:verify_multisig(Artifact, Proofs, MultiKeys) of
true -> ok;
false -> throw({error, insufficient_votes})
end
end;
_ ->
{ok, MasterKey} = blockchain_ledger_v1:master_key(Ledger),
case verify_key(Artifact, MasterKey, proof(Txn)) of
true -> ok;
_ -> throw({error, bad_block_proof})
end
end;
_ ->
{ok, MasterKey} = blockchain_ledger_v1:master_key(Ledger),
case verify_key(Artifact, MasterKey, proof(Txn)) of
true ->
ok;
_ ->
throw({error, bad_block_proof})
end
end
end,
%% TODO: validate that a cancelled transaction is actually on
%% the chain
%% TODO: figure out how to validate that predicate functions
%% actually exist when set, without breaking applications like
%% the router and the API that only want to validate vars.
ok
catch throw:Ret ->
lager:error("invalid chain var transaction: ~p reason ~p", [Txn, Ret]),
Ret
end;
1 ->
legacy_is_valid(Txn, Chain)
end.
-spec legacy_is_valid(txn_vars(), blockchain:blockchain()) -> ok | {error, any()}.
legacy_is_valid(Txn, Chain) ->
Ledger = blockchain:ledger(Chain),
Vars = decode_vars(vars(Txn)),
Artifact = term_to_binary(Vars, [{compressed, 9}]),
lager:debug("validating vars ~p artifact ~p", [Vars, Artifact]),
try
Gen =
case blockchain_ledger_v1:current_height(Ledger) of
{ok, 0} ->
true;
_ ->
false
end,
Nonce = nonce(Txn),
case blockchain_ledger_v1:vars_nonce(Ledger) of
{ok, LedgerNonce} when Nonce > LedgerNonce ->
ok;
{error, not_found} when Gen == true ->
ok;
_ ->
throw({error, bad_nonce})
end,
%% here we can accept a valid master key
case master_key(Txn) of
<<>> when Gen == true ->
throw({error, genesis_requires_master_key});
<<>> ->
ok;
Key ->
KeyProof =
case key_proof(Txn) of
<<>> ->
throw({error, no_master_key_proof}),
<<>>;
P ->
P
end,
case verify_key(Artifact, Key, KeyProof) of
true ->
ok;
_ ->
throw({error, bad_master_key})
end
end,
case Gen of
true ->
%% genesis block requires master key and has already
%% validated the proof if it has made it here.
ok;
_ ->
{ok, MasterKey} = blockchain_ledger_v1:master_key(Ledger),
case verify_key(Artifact, MasterKey, proof(Txn)) of
true -> ok;
_ -> throw({error, bad_block_proof})
end
end,
lists:foreach(
fun(VarName) ->
case blockchain:config(VarName, Ledger) of % ignore this one using "?"
{ok, _} -> ok;
{error, not_found} -> throw({error, {unset_var_not_set, VarName}})
end
end,
decode_unsets(unsets(Txn))),
%% TODO: validate that a cancelled transaction is actually on
%% the chain
%% TODO: figure out how to validate that predicate functions
%% actually exist when set, without breaking applications like
%% the router and the API that only want to validate vars.
ok
catch throw:Ret ->
lager:error("invalid chain var transaction: ~p reason ~p", [Txn, Ret]),
Ret
end.
validate_master_keys(Txn, Gen, Artifact, Ledger) ->
case blockchain:config(?use_multi_keys, Ledger) of
{ok, true} ->
case multi_keys(Txn) of
[] when Gen == true ->
throw({error, genesis_requires_multi_keys});
[] ->
ok;
MultiKeys ->
MaxProofs = length(MultiKeys),
%% in order for a new key set to be valid, we need to make sure that all new
%% keys have a valid proof associated with them, much like the old master key
%% system uses its singular proof to ensure that we have a valid and known key.
%% the more complicated logic here is to make sure we don't have to re-prove old
%% keys, and to ensure that all new keys have one proof associated with them.
OldMultiKeys = case blockchain_ledger_v1:multi_keys(Ledger) of
{ok, Keys} -> Keys;
{error, not_found} -> []
end,
%% remove all existing keys from the new list. They don't need to re-prove
%% themselves and cannot 'vote' for the change here. Their votes as to the
%% signedness of the transaction are counted elsewhere.
ProofKeys = MultiKeys -- OldMultiKeys,
KeyProofs =
%% deduplicate the proofs
case lists:usort(multi_key_proofs(Txn)) of
[] ->
throw({error, no_multi_keys_proofs});
Ps ->
Ps
end,
%% count_votes here counts the number of proofs that can be validated by the
%% keys in MultiKeys, with each key only being allowed to be used once.
case length(KeyProofs) > MaxProofs of
true -> throw({error, too_many_key_proofs});
false ->
Votes = blockchain_utils:count_votes(Artifact, MultiKeys, KeyProofs),
%% ProofKeys here is the number of new keys in the list of multi-keys, so if the
%% 'vote count' is equal to the number of keys, then every key has a valid proof.
case Votes == length(ProofKeys) of
true ->
ok;
_ ->
lager:warning("not enough votes: votes ~p new keys ~p",
[Votes, length(ProofKeys)]),
throw({error, bad_multi_key_proof})
end
end
end;
_ ->
case master_key(Txn) of
<<>> when Gen == true ->
throw({error, genesis_requires_master_key});
<<>> ->
ok;
Key ->
KeyProof =
case key_proof(Txn) of
<<>> ->
throw({error, no_master_key_proof}),
<<>>;
P ->
P
end,
case verify_key(Artifact, Key, KeyProof) of
true ->
ok;
_ ->
throw({error, bad_master_key})
end
end
end.
%% TODO: we need a generalized hook here for when chain vars change
%% and invalidate something in the ledger, to enable stuff to stay consistent
-spec absorb(txn_vars(), blockchain:blockchain()) -> ok | {error, atom()} | {error, {atom(), any()}}.
absorb(Txn, Chain) ->
Ledger = blockchain:ledger(Chain),
%% we absorb the nonce here to prevent replays of this txn, even
%% if we cannot absorb the full txn right now.
ok = blockchain_ledger_v1:vars_nonce(nonce(Txn), Ledger),
case maybe_absorb(Txn, Ledger, Chain) of
true ->
ok;
false ->
ok = blockchain_ledger_v1:save_threshold_txn(Txn, Ledger)
end.
%% in a rescue situation, we apply vars immediately.
rescue_absorb(Txn, Chain) ->
Ledger = blockchain:ledger(Chain),
delayed_absorb(Txn, Ledger).
maybe_absorb(Txn, Ledger, _Chain) ->
case blockchain_ledger_v1:current_height(Ledger) of
%% genesis block is never delayed
{ok, 0} ->
delayed_absorb(Txn, Ledger),
true;
_ ->
{ok, Height} = blockchain_ledger_v1:current_height(Ledger),
{ok, Delay} = blockchain:config(?vars_commit_delay, Ledger),
Effective = Delay + Height,
case version_predicate(Txn) of
0 ->
ok = blockchain_ledger_v1:delay_vars(Effective, Txn, Ledger),
true;
V ->
{ok, Members} = blockchain_ledger_v1:consensus_members(Ledger),
%% TODO: combine these checks for efficiency?
case check_members(Members, V, Ledger) of
true ->
{ok, Threshold} = blockchain:config(?predicate_threshold, Ledger),
Versions = blockchain_ledger_v1:cg_versions(Ledger),
case sum_higher(V, Versions) of
Pct when Pct >= Threshold andalso Delay =:= 0 ->
delayed_absorb(Txn, Ledger),
true;
Pct when Pct >= Threshold ->
ok = blockchain_ledger_v1:delay_vars(Effective, Txn, Ledger),
true;
_Pct ->
false
end;
_ ->
false
end
end
end.
check_members(Members, Target, Ledger) ->
case blockchain_ledger_v1:config(?election_version, Ledger) of
{ok, N} when N >= 5 ->
lists:all(
fun(M) ->
case blockchain_ledger_v1:get_validator(M, Ledger) of
{ok, Val} ->
V = blockchain_ledger_validator_v1:version(Val),
V >= Target;
_Err -> false
end
end,
Members);
_ ->
lists:all(
fun(M) ->
case blockchain_ledger_v1:find_gateway_info(M, Ledger) of
{ok, Gw} ->
V = blockchain_ledger_gateway_v2:version(Gw),
V >= Target;
_ -> false
end
end,
Members)
end.
delayed_absorb(Txn, Ledger) ->
Vars = decode_vars(vars(Txn)),
Unsets = decode_unsets(unsets(Txn)),
ok = blockchain_ledger_v1:vars(Vars, Unsets, Ledger),
ok = process_hooks(Vars, Unsets, Ledger),
case blockchain:config(?use_multi_keys, Ledger) of
{ok, true} ->
case multi_keys(Txn) of
[] ->
ok;
Keys ->
ok = blockchain_ledger_v1:multi_keys(Keys, Ledger)
end;
_ ->
case master_key(Txn) of
<<>> ->
ok;
Key ->
ok = blockchain_ledger_v1:master_key(Key, Ledger)
end
end,
case blockchain_ledger_v1:mode(Ledger) of
active ->
%% we've invalidated the region cache, so prewarm it.
spawn(fun() ->
timer:sleep(30000),
blockchain_region_v1:prewarm_cache(blockchain_ledger_v1:remove_context(Ledger))
end);
_ ->
ok
end,
ok.
sum_higher(Target, Proplist) ->
sum_higher(Target, Proplist, 0).
sum_higher(_Target, [], Sum) ->
Sum;
sum_higher(Target, [{Vers, Pct}| T], Sum) ->
case Vers >= Target of
true ->
sum_higher(Target, T, Sum + Pct);
false ->
sum_higher(Target, T, Sum)
end.
decode_unsets(Unsets) ->
lists:map(fun(U) -> binary_to_atom(U, utf8) end, Unsets).
-spec print(txn_vars()) -> iodata().
print(undefined) -> <<"type=vars undefined">>;
print(#blockchain_txn_vars_v1_pb{vars = Vars, version_predicate = VersionP,
master_key = MasterKey, key_proof = KeyProof,
multi_keys = MultiKeys, multi_key_proofs = MultiKeyProofs,
unsets = Unsets, cancels = Cancels,
nonce = Nonce}) ->
io_lib:format("type=vars vars=~p nonce=~p unsets=~p version_predicate=~p master_key=~p key_proof=~p "
"multi_keys=~p multi_key_proofs=~p cancels=~p",
[Vars, Nonce, Unsets, VersionP,
MasterKey, KeyProof,
MultiKeys, MultiKeyProofs, Cancels]).
json_type() ->
<<"vars_v1">>.
-spec to_json(txn_vars(), blockchain_json:opts()) -> blockchain_json:json_object().
to_json(Txn, _Opts) ->
#{
type => ?MODULE:json_type(),
hash => ?BIN_TO_B64(hash(Txn)),
vars => maps:map(fun(_, V) when is_binary(V) ->
case lists:all(fun(C) -> C >= 32 andalso C =< 127 end, binary_to_list(V)) of
true ->
V;
false ->
base64:encode(V)
end;
(_, V) -> V
end, decoded_vars(Txn)),
version_predicate => version_predicate(Txn),
proof => ?BIN_TO_B64(proof(Txn)),
master_key => ?MAYBE_B58(master_key(Txn)),
key_proof => ?BIN_TO_B64(key_proof(Txn)),
cancels => cancels(Txn),
unsets => unsets(Txn),
nonce => nonce(Txn)
}.
-spec process_hooks(Vars :: map(), Unsets :: list(), Ledger :: blockchain_ledger_v1:ledger()) -> ok.
process_hooks(Vars, Unsets, Ledger) ->
_ = maps:map(
fun(Var, Value) ->
?MODULE:var_hook(Var, Value, Ledger)
end, Vars),
_ = lists:foreach(
fun(Var) ->
?MODULE:unset_hook(Var, Ledger)
end, Unsets),
ok.
%% Separate out hook functions and call them in separate functions below the hook section.
-spec var_hook(Var :: atom(), Value :: any(), Ledger :: blockchain_ledger_v1:ledger()) -> ok.
var_hook(?poc_targeting_version, 6, Ledger) ->
%% purge any active POCs
purge_pocs(Ledger),
%% build the h3dex lookup
{ok, Res} = blockchain_ledger_v1:config(?poc_target_hex_parent_res, Ledger),
blockchain_ledger_v1:build_random_hex_targeting_lookup(Res, Ledger),
ok;
var_hook(?poc_targeting_version, 5, Ledger) ->
%% purge any active POCs
purge_pocs(Ledger),
%% v3 targeting enabled, remove the h3dex lookup
blockchain_ledger_v1:clean_random_hex_targeting_lookup(Ledger),
ok;
var_hook(?poc_targeting_version, 4, Ledger) ->
%% v4 targeting enabled, build the h3dex lookup
{ok, Res} = blockchain_ledger_v1:config(?poc_target_hex_parent_res, Ledger),
blockchain_ledger_v1:build_random_hex_targeting_lookup(Res, Ledger),
ok;
var_hook(?poc_targeting_version, 3, Ledger) ->
%% v3 targeting enabled, remove the h3dex lookup
blockchain_ledger_v1:clean_random_hex_targeting_lookup(Ledger),
ok;
var_hook(?poc_target_hex_parent_res, Value, Ledger) ->
%% targeting resolution changed, rebuild h3dex lookup
blockchain_ledger_v1:clean_random_hex_targeting_lookup(Ledger),
blockchain_ledger_v1:build_random_hex_targeting_lookup(Value, Ledger),
ok;
var_hook(?poc_hexing_type, h3dex, Ledger) ->
%% the hexes keys should be safe to remove now
blockchain_ledger_v1:clean_all_hexes(Ledger),
ok;
var_hook(?poc_hexing_type, hex_h3dex, Ledger) ->
%% rebuild hexes since we're back to updating them
blockchain:bootstrap_hexes(Ledger),
ok;
%% poc challenger type has been modified
%% we want to clear out the pocs CF
%% we dont care about its value, if its been
%% updated then we wipe all POCs
var_hook(?poc_challenger_type, Type, Ledger) ->
case Type of
validator ->
Ct =
blockchain_ledger_v1:fold_validators(
fun(Val, Acc) ->
case blockchain_ledger_validator_v1:status(Val) of
staked ->
Acc + 1;
_ -> Acc
end
end,
0,
Ledger),
blockchain_ledger_v1:validator_count(Ct, Ledger);
_ -> ok
end,
purge_pocs(Ledger),
ok;
var_hook(?ledger_entry_version, 2, Ledger) ->
%% Migrate to new style ledger entries
blockchain_ledger_v1:migrate_entries(Ledger),
ok;
var_hook(_Var, _Value, _Ledger) ->
ok.
-spec unset_hook(Var :: atom(), Ledger :: blockchain_ledger_v1:ledger()) -> ok.
unset_hook(?poc_targeting_version, Ledger) ->
%% going back to the default, which is v3 so remove the h3dex lookup
blockchain_ledger_v1:clean_random_hex_targeting_lookup(Ledger),
ok;
unset_hook(?poc_hexing_type, Ledger) ->
%% rebuild hexes since we're back to updating them
blockchain:bootstrap_hexes(Ledger),
ok;
unset_hook(?poc_challenger_type, Ledger) ->
purge_pocs(Ledger),
ok;
unset_hook(_Var, _Ledger) ->
ok.
%%%
%%% Helper API
%%%
create_proof(Key, Txn) ->
B = create_artifact(Txn),
SignFun = libp2p_crypto:mk_sig_fun(Key),
SignFun(B).
legacy_create_proof(Key, Vars) ->
B = term_to_binary(Vars, [{compressed, 9}]),
SignFun = libp2p_crypto:mk_sig_fun(Key),
SignFun(B).
%%% helper functions
create_artifact(Txn) ->
Txn1 = unset_proofs(Txn),
blockchain_txn_vars_v1_pb:encode_msg(Txn1).
verify_key(_Artifact, _Key, <<>>) ->
throw({error, no_proof});
verify_key(Artifact, Key, Proof) ->
libp2p_crypto:verify(Artifact, Proof, libp2p_crypto:bin_to_pubkey(Key)).
validate_int(Value, Name, Min, Max, InfOK) ->
case is_integer(Value) of
false when InfOK == true andalso Value == infinity ->
ok;
false ->
throw({error, {list_to_atom("non_integral_" ++ Name), Value}});
true ->
case Value >= Min andalso Value =< Max of
false ->
throw({error, {list_to_atom(Name ++ "_out_of_range"), min, Min, val, Value, max, Max}});
_ -> ok
end
end.
validate_float(Value, Name, Min, Max) ->
case is_float(Value) of
false when Value == infinity ->
ok;
false ->
throw({error, {list_to_atom("non_float_" ++ Name), Value}});
true ->
case Value >= Min andalso Value =< Max of
false ->
throw({error, {list_to_atom(Name ++ "_out_of_range"), min, Min, val, Value, max, Max}});
_ -> ok
end
end.
validate_oracle_public_keys_format(Str) when is_binary(Str) ->
PubKeys = blockchain_utils:bin_keys_to_list(Str),
validate_oracle_keys(PubKeys).
validate_oracle_keys([]) -> ok;
validate_oracle_keys([H|T]) ->
try
_ = libp2p_crypto:bin_to_pubkey(H),
validate_oracle_keys(T)
catch
_C:_E:_St ->
throw({error, {invalid_oracle_pubkey, H}})
end.
validate_staking_keys_format(Str) when is_binary(Str) ->
PubKeys = blockchain_utils:bin_keys_to_list(Str),
validate_staking_keys(PubKeys).
validate_staking_keys([]) -> ok;
validate_staking_keys([H|T]) ->
try
_ = libp2p_crypto:bin_to_pubkey(H),
validate_staking_keys(T)
catch
_C:_E:_St ->
throw({error, {invalid_staking_pubkey, H}})
end.
validate_staking_keys_to_mode_mappings_format(Bin) when is_binary(Bin) ->
Mappings = blockchain_utils:bin_to_prop(Bin, 8),
validate_staking_keys_to_mode_mappings(Mappings);
validate_staking_keys_to_mode_mappings_format(_Bin) ->
throw({error, invalid_staking_to_mode_mappings_format}).
validate_staking_keys_to_mode_mappings([]) -> ok;
validate_staking_keys_to_mode_mappings([{PubKey, GWMode} | T]) ->
try
_ = libp2p_crypto:bin_to_pubkey(PubKey),
_ = validate_staking_key_mode_mapping_value(GWMode),
validate_staking_keys_to_mode_mappings(T)
catch
_C:_E:_St ->
throw({error, {invalid_staking_to_mode_mapping, {PubKey, GWMode}}})
end.
validate_staking_key_mode_mapping_value(GWMode) when GWMode == <<"dataonly">>;
GWMode == <<"light">>;
GWMode == <<"full">> ->
ok;
validate_staking_key_mode_mapping_value(GWMode) ->
throw({error, {invalid_staking_to_mode_mapping_value, GWMode}}).
%% ALL VALIDATION ERRORS MUST THROW ERROR TUPLES
%%
%% election vars
validate_var(?election_version, Value) ->
case Value of
undefined -> ok;
2 -> ok;
3 -> ok;
4 -> ok;
5 -> ok; % validator move trigger
6 -> ok; % move to maps
_ ->
throw({error, {invalid_election_version, Value}})
end;
validate_var(?election_selection_pct, Value) ->
validate_int(Value, "election_selection_pct", 1, 99, false);
validate_var(?election_removal_pct, Value) ->
validate_int(Value, "election_removal_pct", 1, 99, false);
validate_var(?election_cluster_res, Value) ->
validate_int(Value, "election_cluster_res", 0, 15, false);
validate_var(?election_replacement_factor, Value) ->
validate_int(Value, "election_replacement_factor", 1, 100, false);
validate_var(?election_replacement_slope, Value) ->
validate_int(Value, "election_replacement_slope", 1, 100, false);
validate_var(?election_interval, Value) ->
validate_int(Value, "election_interval", 3, 100, true);
validate_var(?election_restart_interval, Value) ->
validate_int(Value, "election_restart_interval", 5, 100, false);
validate_var(?election_restart_interval_range, Value) ->
validate_int(Value, "election_restart_interval_range", 1, 5, false);
validate_var(?election_bba_penalty, Value) ->
validate_float(Value, "election_bba_penalty", 0.001, 0.5);
validate_var(?election_seen_penalty, Value) ->
validate_float(Value, "election_seen_penalty", 0.001, 0.5);
%% ledger vars
validate_var(?var_gw_inactivity_threshold, Value) ->
validate_int(Value, "var_gw_inactivity_threshold", 15, 2880, false);
validate_var(?witness_refresh_interval, Value) ->
validate_int(Value, "witness_refresh_interval", 1, 20000, false);
validate_var(?witness_refresh_rand_n, Value) ->
validate_int(Value, "witness_refresh_rand_n", 50, 1000, false);
%% meta vars
validate_var(?vars_commit_delay, Value) ->
validate_int(Value, "vars_commit_delay", 1, 60, false);
validate_var(?chain_vars_version, Value) ->
case Value of
1 -> ok;
2 -> ok;
_ ->
throw({error, {chain_vars_version, Value}})
end;
validate_var(?predicate_threshold, Value) ->
validate_float(Value, "predicate_threshold", 0.0, 1.0);
validate_var(?predicate_callback_mod, Value) ->
case Value of
miner ->
ok;
_ ->
throw({error, {predicate_callback_mod, Value}})
end;
validate_var(?predicate_callback_fun, Value) ->
case lists:member(Value, ?allowed_predicate_funs) of
true ->
ok;
_ ->
throw({error, {predicate_callback_fun, Value}})
end;
%% miner vars
validate_var(?num_consensus_members, Value) ->
validate_int(Value, "num_consensus_members", 4, 100, false),
case (Value - 1) rem 3 == 0 of
true ->
ok;
false ->
throw({error, {num_consensus_members_not_3fplus1, Value}})
end;
validate_var(?block_time, Value) ->
validate_int(Value, "block_time", 2, timer:minutes(10), false);
validate_var(?batch_size, Value) ->
validate_int(Value, "batch_size", 10, 10000, false);
validate_var(?block_version, Value) ->
case Value of
v1 ->
ok;
_ ->
throw({error, {invalid_block_version, Value}})
end;
validate_var(?dkg_curve, Value) ->
case Value of
'SS512' ->
ok;
_ ->
throw({error, {invalid_dkg_curve, Value}})
end;
%% burn vars
validate_var(?token_burn_exchange_rate, Value) ->
case is_integer(Value) andalso Value >= 0 of
true ->
ok;
_ ->
throw({error, {invalid_token_burn_exchange_rate, Value}})
end;
%% poc related vars
validate_var(?h3_exclusion_ring_dist, Value) ->
validate_int(Value, "h3_exclusion_ring_dist", 1, 10, false);
validate_var(?h3_max_grid_distance, Value) ->
validate_int(Value, "h3_max_grid_distance", 1, 500, false);
validate_var(?h3_neighbor_res, Value) ->
validate_int(Value, "h3_neighbor_res", 0, 15, false);