forked from TrueCloudLab/frostfs-node
Compare commits
836 commits
feature/87
...
master
Author | SHA1 | Date | |
---|---|---|---|
fa08bfa553 | |||
0da998ef50 | |||
e44782473a | |||
9cd1bcef06 | |||
ca0a33ea0f | |||
f6c5222952 | |||
ea868e09f8 | |||
31d3d299bf | |||
b5b4f78b49 | |||
2832f44437 | |||
7c3bcb0f44 | |||
e64871c3fd | |||
303cd35a01 | |||
bb9ba1bce2 | |||
db03742d33 | |||
148d68933b | |||
51ee132ea3 | |||
226dd25dd0 | |||
bd0197eaa8 | |||
e44b84c18c | |||
bed49e6ace | |||
df05057ed4 | |||
b6c8ebf493 | |||
6e82661c35 | |||
1a091ea7bb | |||
7ac3542714 | |||
f0c43c8d80 | |||
8ba9f31fca | |||
2af3409d39 | |||
d165ac042c | |||
7151c71d51 | |||
91d9dc2676 | |||
7853dbc315 | |||
3821645085 | |||
72470d6b48 | |||
e9837bbcf9 | |||
a641c91594 | |||
b1614a284d | |||
d0ce835fbf | |||
dfa51048a8 | |||
670305a721 | |||
1f6cf57e30 | |||
386a12eea4 | |||
15139d80c9 | |||
41da27dad5 | |||
ac0511d214 | |||
7e542906ef | |||
d1bc4351c3 | |||
1c12f23b84 | |||
a353d45742 | |||
d5c46d812a | |||
d5d5ce2074 | |||
7df3520d48 | |||
5fe78e51d1 | |||
84b4051b4d | |||
6a51086030 | |||
5c3b2d95ba | |||
2d5d4093be | |||
e3487d5af5 | |||
e37dcdf88b | |||
6c679d1535 | |||
281d65435e | |||
b348b20289 | |||
748edd1999 | |||
47dfd8840c | |||
432042c534 | |||
9cabca9dfe | |||
60feed3b5f | |||
635a292ae4 | |||
edfa3f4825 | |||
e0ac3a583f | |||
00c608c05e | |||
bba1892fa1 | |||
01acec708f | |||
aac65001e5 | |||
1170370753 | |||
9e275d44c8 | |||
2469e0c683 | |||
a6ef4ab524 | |||
49959c4166 | |||
61ee1b5610 | |||
b10c954377 | |||
1605391628 | |||
b1766e47c7 | |||
caa4253249 | |||
7eac5fb18b | |||
0e5524dac7 | |||
3ebd560f42 | |||
1ed7ab75fb | |||
99f9e59de9 | |||
256f96e252 | |||
e5ea95c045 | |||
9073e555db | |||
2771fdb8c7 | |||
efa4ce00b8 | |||
f12f04199e | |||
2e2c62147d | |||
6ae8667fb4 | |||
49a4e727fd | |||
2e974f734c | |||
3042490340 | |||
a339b52a60 | |||
4ab4ed6f96 | |||
3b1364e4cf | |||
daff77b273 | |||
7a7ee71a4d | |||
ffe9906266 | |||
ae31ef3602 | |||
e2cb0640f1 | |||
9f4ce600ac | |||
d82f0d1926 | |||
acd5babd86 | |||
b65874d1c3 | |||
69c63006da | |||
d77a218f7c | |||
44df67492f | |||
1e6f132b4e | |||
6dc0dc6691 | |||
f7cb6b4d87 | |||
7fc6101bec | |||
7ef36749d0 | |||
c6066d6ee4 | |||
612b34d570 | |||
7429553266 | |||
6921a89061 | |||
16598553d9 | |||
c139892117 | |||
62b5181618 | |||
6db46257c0 | |||
c16dae8b4d | |||
fd004add00 | |||
8ed7a676d5 | |||
b451de94c8 | |||
f1556e3c42 | |||
e122ff6013 | |||
e2658c7519 | |||
c00f4bab18 | |||
46fef276b4 | |||
9bd05e94c8 | |||
16830033f8 | |||
1cf51a8079 | |||
3324c26fd8 | |||
a692298533 | |||
be2753de00 | |||
b543569c3f | |||
80f8a8fd3a | |||
2f3bc6eb84 | |||
8a57c78f5f | |||
ad01fb958a | |||
d336f2d487 | |||
c82c753e9f | |||
f666898e5d | |||
b1a31281e4 | |||
764450d04a | |||
755cae3f19 | |||
9b13a18aac | |||
ef64930fef | |||
c8fb154151 | |||
7edec9193c | |||
3cf6ea745d | |||
9a77527f46 | |||
5b1ba8e23d | |||
9902965ff4 | |||
33ad753302 | |||
15102e6dfd | |||
17ec84151b | |||
6c45a17af6 | |||
d19ab43500 | |||
5bcf81d1cc | |||
c2effcc61c | |||
2285cfc36f | |||
e74d05c03f | |||
48862e0e63 | |||
89892d9754 | |||
7ac0852364 | |||
d28a5d2d7a | |||
87ac3c5279 | |||
d5ee6d3039 | |||
433aab12bb | |||
81f4cdbb91 | |||
3cd7d23f10 | |||
012af5cc38 | |||
eb5336d5ff | |||
bc8d79ddf9 | |||
29708b78d7 | |||
b9284604d9 | |||
65a4320c75 | |||
9a260c2e64 | |||
6f798b9c4b | |||
e515dd4582 | |||
8b6ec57c61 | |||
ed13387c0e | |||
5afea62ec0 | |||
c0a2f20eee | |||
2d064d0bd8 | |||
ef38420623 | |||
f7caef355b | |||
fbdfd503e4 | |||
67798bb50e | |||
5b653aa65f | |||
e314f328c4 | |||
6c96cc2af6 | |||
74db735265 | |||
3304afa9d1 | |||
b42bcdc6fa | |||
b0c5def2d9 | |||
90f3669399 | |||
07ce40e119 | |||
41038b2ec0 | |||
d83879d4b8 | |||
f6582081a4 | |||
00b1cecfb7 | |||
63466d71b2 | |||
d53732f663 | |||
3012286452 | |||
714ff784fa | |||
d2a59b2de8 | |||
acd6eb1815 | |||
42bf03e5cc | |||
5992ee901a | |||
dfb00083d0 | |||
1134760271 | |||
02bb7159a5 | |||
94302235d0 | |||
cc5360a578 | |||
4190fba86d | |||
936ebbb8e5 | |||
c065d55ca3 | |||
fe9f664b57 | |||
87f4b934d1 | |||
8093e145b3 | |||
3da168f8cf | |||
4572fa4874 | |||
1efa64ee72 | |||
be744ae3e6 | |||
1b520f7973 | |||
899cd55c27 | |||
0c49bca19c | |||
5fbb2657ca | |||
a5de74a249 | |||
fc032838c0 | |||
2f710d8f94 | |||
4dc9a1b300 | |||
963faa615a | |||
9a87acb87a | |||
9206ce5cd2 | |||
6c46044c9c | |||
01e3944b31 | |||
434048e8d9 | |||
f83f7feb8c | |||
62028cd7ee | |||
f45e75e3eb | |||
57c31e9802 | |||
9c5ddc4dfe | |||
54eb005822 | |||
a13219808a | |||
7f8a1dcf8e | |||
d0ed29b3c7 | |||
5f22ba6f38 | |||
a5e1aa22c9 | |||
772b471aab | |||
4fbfffd44c | |||
29e4cf7ba1 | |||
a2ab6d4942 | |||
bdd57c8b6b | |||
d1d6e3471c | |||
401c398704 | |||
004ff9e9bf | |||
63a567a1de | |||
580cd55180 | |||
e319bf403e | |||
aedb55f913 | |||
b69e07da7a | |||
2bd560e528 | |||
95597d3437 | |||
fd18aa363b | |||
76268e3ea2 | |||
8434f3dbfc | |||
34e6a309c6 | |||
bdf386366c | |||
839dead226 | |||
3bb65ba820 | |||
d4493a6d08 | |||
0b87be804a | |||
f71418b73c | |||
c34b8acedd | |||
c290d079fd | |||
53a90634fc | |||
5a53f9c4fd | |||
1361db91ee | |||
945b7c740b | |||
61d5e140e0 | |||
3441fff05d | |||
ac1eee091d | |||
a603d14d08 | |||
d4be2f20d4 | |||
e5c8f7ff9f | |||
1e7f9909da | |||
b807d8c400 | |||
d4bec24c9f | |||
ea48e928c8 | |||
96308a26c6 | |||
74a6a1da7f | |||
2be1aa781d | |||
89d0435b1d | |||
54fe8383a4 | |||
944160427b | |||
bb44867491 | |||
546d09660f | |||
e3764c51df | |||
b33559754d | |||
f345fe9a58 | |||
3b236160a6 | |||
25d2ae8aaf | |||
e39378b1c3 | |||
8a6e3025a0 | |||
2dd3a6f7a8 | |||
b142b6f48e | |||
5f6c7cbdb1 | |||
66e17f4b8e | |||
99be4c83a7 | |||
ec8da40567 | |||
dea6f031f9 | |||
5fac4058e8 | |||
2220f6a809 | |||
a812932984 | |||
92fe5d90f5 | |||
4668efc0bf | |||
654d970fad | |||
d3b209c8e1 | |||
edb1747af7 | |||
a61201a987 | |||
6b6eabe41c | |||
d508da8397 | |||
007827255e | |||
f652518c24 | |||
273980cfb9 | |||
108e4e07be | |||
b3deb893ba | |||
7768a482b5 | |||
371d97f61a | |||
e655336390 | |||
ed396448ac | |||
9cbd32bce8 | |||
1ae86f35a8 | |||
b9043433a0 | |||
a4fb7f085b | |||
a685fcdc96 | |||
2b3fc50681 | |||
98fe24cdb7 | |||
882c068410 | |||
6c2146bbc1 | |||
03976c6ed5 | |||
7e97df4878 | |||
01b6f1733c | |||
7abbdca064 | |||
6488ddee88 | |||
d6b42972a8 | |||
5e9a97fd3e | |||
fa7f9fbce2 | |||
806ea37101 | |||
80099d9a2f | |||
a059a7dcf0 | |||
bd24beecf8 | |||
dfe825b81b | |||
76f67ea34e | |||
7d0d781db1 | |||
0f08a2efba | |||
7bf20c9f1f | |||
2542d4f5df | |||
15dae8685e | |||
7bca428db0 | |||
a345c972bf | |||
8c1082b31a | |||
cfda9003a7 | |||
6ff0b0996b | |||
8319b59238 | |||
b7acb34fa4 | |||
41104f2383 | |||
eeab417dcf | |||
5ed317e24c | |||
e890f1b4b1 | |||
a4a1c3f18b | |||
ec1509de4e | |||
5da41f1fe5 | |||
d055168e2a | |||
80ce7c3a00 | |||
93d63e1632 | |||
68029d756e | |||
fa82854af4 | |||
c985b1198f | |||
08b1f18bca | |||
36efccd862 | |||
5c01bd5be8 | |||
8e51d7849a | |||
10602b55b1 | |||
eeca796d2e | |||
327d364f34 | |||
dc3dcabadc | |||
8021bacc43 | |||
ef4cea6d19 | |||
a55600893e | |||
c49982d22a | |||
7e04083c27 | |||
a12c39667d | |||
85a77b7c21 | |||
8377372a40 | |||
dd459d399f | |||
7fd7961dfa | |||
8398a8b4b3 | |||
9c2c76ca32 | |||
1032075a21 | |||
94f07b4778 | |||
7ddba70030 | |||
658e3cb92f | |||
9ee1bd3669 | |||
ca4d6df1cc | |||
18182e578e | |||
3119f2fbc3 | |||
e377a92d97 | |||
eadcea8df0 | |||
5e5ee545b6 | |||
27caa8a72f | |||
e83d39e33f | |||
fc383ea6ae | |||
00a88b9936 | |||
3940bc17c1 | |||
e5767c9002 | |||
286df198c9 | |||
3a48b282b6 | |||
21431f22c0 | |||
d5dc14c639 | |||
39866a957c | |||
d02a7c2d38 | |||
08953a2f94 | |||
0308835d48 | |||
36956db123 | |||
3bf6e6dde6 | |||
b027a7f91e | |||
6ace2f597e | |||
784e8ef857 | |||
ca974b8b4c | |||
84ecd61dfd | |||
6ef38c07bd | |||
d90aab5454 | |||
0c2b6f3dac | |||
47bcd346d3 | |||
8eb591d668 | |||
cfd5e3d403 | |||
62cbb72a5e | |||
78b1d9b18d | |||
40c9ddb6ba | |||
3a797e4682 | |||
2bac82cd6f | |||
bbe95dac8b | |||
80d7459560 | |||
4bd4667791 | |||
f3a861806e | |||
a378ff9cf6 | |||
91bed3b0ba | |||
74842e7f43 | |||
259007540f | |||
56eeb630b6 | |||
36eab4059c | |||
72ab373b71 | |||
7a8ac4907a | |||
10497e9136 | |||
dc2867682f | |||
dc6778f385 | |||
7085723c6b | |||
4c7ff159ec | |||
81070ada01 | |||
452faa3c89 | |||
87a4a6e8d0 | |||
4f7d76c9ef | |||
4951babd5f | |||
a0e5fc733e | |||
df894fbac7 | |||
81ea91de52 | |||
11a38a0a84 | |||
0b87388c18 | |||
621dbf58ab | |||
a1f7615b7e | |||
46732b61d7 | |||
a83eeddb1d | |||
9ac74efc41 | |||
ec76689ab7 | |||
68eb68f59a | |||
11e880de7f | |||
40b68bcb6c | |||
fd28461def | |||
ecd1ed7a5e | |||
ac1f014747 | |||
7b8937ec35 | |||
75eedf71f3 | |||
5b100699d7 | |||
76cf7a051b | |||
b9d6c9d10c | |||
3fc8e0e08c | |||
dbd3b238f7 | |||
96fe271bab | |||
a0e49fa5a5 | |||
42ecc2f2b9 | |||
68ac490729 | |||
6a39c3d15e | |||
9d73f9c2c6 | |||
41e670c9ba | |||
d4f425f86a | |||
b9fcaad21f | |||
069c1559cc | |||
6cf512e574 | |||
e7d479f4c2 | |||
a0c588263b | |||
239323eeef | |||
04a3f891fd | |||
4edff5eea6 | |||
a90310335d | |||
a849236b68 | |||
67b3002743 | |||
3f1961157e | |||
2e074d3846 | |||
8fcd0f8f8d | |||
806236da78 | |||
6f2187a420 | |||
cc2449beaf | |||
643480d6fa | |||
f2d2908745 | |||
5aacb8fc86 | |||
f8e33f8e3a | |||
f0edebea18 | |||
0b367007fc | |||
92e19feb57 | |||
c1af13b47e | |||
9f80d6d9a2 | |||
6130650bb6 | |||
88b8ddd902 | |||
a82c8cc5b8 | |||
d355274cd0 | |||
3555c73225 | |||
e43e7bec3a | |||
50923ed81c | |||
4a34d0d40e | |||
cc3f762cf2 | |||
3627b44e92 | |||
482c5129ac | |||
43625e7536 | |||
2b02f52cd9 | |||
542d3adcb2 | |||
51ade979e8 | |||
2697d4d1fe | |||
40b04c00ef | |||
89a80e9a0f | |||
8fd678e269 | |||
436c9f5558 | |||
44f2e8f27f | |||
0e42126ddc | |||
1cd8562db8 | |||
4ab6c404f7 | |||
cbe9757490 | |||
d45d086acd | |||
af57d5a6a1 | |||
2f04ce2f79 | |||
b078fe5ba1 | |||
f3e09cb09b | |||
5c582e96fd | |||
b3eaa8a9bc | |||
0924b62a95 | |||
300654b045 | |||
b4cfc80579 | |||
d0f64c23a5 | |||
6e71ae3bda | |||
bf9bdde8ea | |||
952d13cd2b | |||
20baf6e112 | |||
74135776c7 | |||
0144117cc9 | |||
368218f0cc | |||
a45b548a6f | |||
654384990c | |||
ada1b9f737 | |||
5c730de96e | |||
854200a874 | |||
fe2c1c926f | |||
3e782527b8 | |||
21a490da8f | |||
93c0ccad4f | |||
00b2b77b26 | |||
a23d53b2d4 | |||
fc7b07f314 | |||
9cc51f86b7 | |||
b60a51b862 | |||
6c76c9b457 | |||
45f4e6939d | |||
e07869a8cf | |||
ec2873caa7 | |||
71789676d5 | |||
c9efaa5819 | |||
4730ecfdb8 | |||
52bebe9452 | |||
4b514f5ba0 | |||
c8e2ca2ab4 | |||
3b9d12b11c | |||
411a8d0245 | |||
112a7c690f | |||
167c52a1a9 | |||
700e891b85 | |||
1f02ac2566 | |||
7bc3003803 | |||
6d4583f5de | |||
10ee865e98 | |||
c21d72ac23 | |||
6772976657 | |||
97e54066d0 | |||
46bc6a7930 | |||
3ea1d7b729 | |||
0094186299 | |||
91e79c98ba | |||
e5e0542482 | |||
5be36924e3 | |||
6a46c6d229 | |||
f4dcb418f2 | |||
661faa639e | |||
cdae227f82 | |||
40781b3a20 | |||
5ef5734c4e | |||
669103a33e | |||
2c4b50a71e | |||
2ca5dfc2f6 | |||
3dc81cb4fc | |||
d864945961 | |||
43fdb1da45 | |||
1b17258c04 | |||
e3d9dd6ee8 | |||
57466594fb | |||
1005bf4f56 | |||
76398c06b0 | |||
7b1adfed3e | |||
e74bdaa5d5 | |||
338d8cbebd | |||
5b8200de88 | |||
2b88361849 | |||
f5b67c6735 | |||
bdf4990904 | |||
8668cbf147 | |||
1c5e0f90aa | |||
39da643354 | |||
92569b9bbf | |||
17f7adb640 | |||
0290f86579 | |||
ffb1a6f81a | |||
9aa533e59a | |||
d614f04a0a | |||
531542ce60 | |||
4738508ce2 | |||
ff4c23f59a | |||
17af91619a | |||
4080b99310 | |||
d5194ab2a6 | |||
81a0346a96 | |||
e12fcc041d | |||
f23e38c285 | |||
942d83611b | |||
fd8cdb9671 | |||
0990a9b0bd | |||
8690db697c | |||
c7a12ca3d8 | |||
c09c701613 | |||
5d58b44bc8 | |||
6bf77cabd4 | |||
6959e617c4 | |||
7278201753 | |||
bd216b79cb | |||
d7be70e93f | |||
fb9219af39 | |||
bf70d77844 | |||
11fde3cde4 | |||
5ee5f1df42 | |||
2d595ec15f | |||
7ed07d2dfd | |||
0a600521ad | |||
17f5463389 | |||
31e2396a5f | |||
926cdeb072 | |||
d1d53d2bb6 | |||
7a4b6057ce | |||
f42a529f49 | |||
179b6e64fa | |||
e3579922d8 | |||
5c252c9193 | |||
b4cb54e7ed | |||
6eb63cf5c7 | |||
aa27596d77 | |||
d9fe63ee03 | |||
3195142d67 | |||
d433b49265 | |||
66a26b7775 | |||
dacf580b87 | |||
63a29110ee | |||
0882840bf5 | |||
e5d18e7a85 | |||
b84cf91f73 | |||
c6f0545298 | |||
702351a5d1 | |||
1c504dca5c | |||
b38effd799 | |||
ae5bb87e70 | |||
46a04463b2 | |||
d6534fd755 | |||
6dbb61caf4 | |||
6f25c790aa | |||
93bf9acbc2 | |||
75a1a95c2c | |||
b1d171c261 | |||
7cc368e188 | |||
bc9dbb26ec | |||
61c58e2f92 | |||
9801d08438 | |||
918613546f | |||
2ad433dbcb | |||
abea258b65 | |||
4b13b85173 | |||
e18f0f5178 | |||
7470c383dd | |||
adf7ebab5b | |||
47d9ce71be | |||
0f064b7962 | |||
613e11c4d2 | |||
9611710e19 | |||
9adcb253be | |||
9f68305c2e | |||
dad56d2e98 | |||
4bfc6d29b9 | |||
7627d08914 | |||
3359349acb | |||
946f2ec2bf | |||
9e55836da5 | |||
13d5cd3e21 | |||
f3e50772fd | |||
b871d7a5e8 | |||
6d9707ff1f | |||
d2f13a29de | |||
89784b2e0a | |||
45fd4e4ff1 | |||
e39a714c25 | |||
15fc5bac26 | |||
2680192ba0 | |||
6bafdab004 | |||
05b5f5ca85 | |||
2429508ac5 | |||
5cbf57081f | |||
35370283ba | |||
802192cfef | |||
e2cee4cf09 | |||
814c411f4a | |||
7b0e3f5010 | |||
63c34ea707 | |||
86b2515744 | |||
b8cf0a6b88 | |||
76343f19e5 | |||
e2557b2f0b | |||
9b65f1595a | |||
ce42547980 | |||
9690bd02aa | |||
36fd6c663c | |||
be15eab82a | |||
f7a8f51c66 | |||
beb9d80e34 | |||
8148c9dc19 | |||
218bd72f9a | |||
a92188e5f9 | |||
f6ff3de0ae | |||
77694a2f3b | |||
b68f7be0b6 | |||
bee3741f4e | |||
ba00fc4971 | |||
fdeb99c52f | |||
34fcab3498 | |||
7954c7f8af | |||
cda3a3d834 | |||
0bd030507e | |||
6a5769d1da | |||
3a41858a0f | |||
962e5a9c19 | |||
b36a453238 | |||
abd502215f | |||
fb74524ac7 | |||
7f692409cf | |||
|
fc31b9c947 | ||
ff488b53a1 | |||
9a622a750d | |||
d19ade23c8 | |||
60527abb65 | |||
db67c21d55 | |||
728150d1d2 | |||
e4064c4394 | |||
15d853ea22 | |||
b3f3505ada | |||
a6eb66bf9c | |||
8e2a0611f4 | |||
80b581d499 | |||
805862f4b7 | |||
426cf58b98 | |||
edbe06e07e | |||
cbfeb72466 | |||
053a195ac2 | |||
cfc5ce7853 | |||
c3fa902780 | |||
6010dfdf3d | |||
a6c9a337cd | |||
b1a1b2107d | |||
d7838790c6 | |||
20b4447df7 | |||
9ba48c582d | |||
4358d3c423 | |||
afd2ba9a66 | |||
602ee11123 | |||
c1a5b831b6 | |||
befbaf9d56 | |||
f64c48b157 | |||
9916598dfb | |||
95e15f499f | |||
2cb04379a4 | |||
a5446bc17d | |||
d0eadf7ea2 | |||
6534252c22 | |||
5be2af881a | |||
96c86c4637 | |||
4352bd0e8e | |||
483a67b170 | |||
e3573de6db | |||
c441296592 | |||
675eec91f3 | |||
c681354afd | |||
df055fead5 | |||
c916a75948 | |||
6e2cc32768 |
1074 changed files with 42595 additions and 22454 deletions
|
@ -1,4 +1,4 @@
|
|||
FROM golang:1.21 as builder
|
||||
FROM golang:1.23 AS builder
|
||||
ARG BUILD=now
|
||||
ARG VERSION=dev
|
||||
ARG REPO=repository
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
FROM golang:1.21
|
||||
FROM golang:1.23
|
||||
|
||||
WORKDIR /tmp
|
||||
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
FROM golang:1.21 as builder
|
||||
FROM golang:1.23 AS builder
|
||||
ARG BUILD=now
|
||||
ARG VERSION=dev
|
||||
ARG REPO=repository
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
FROM golang:1.21 as builder
|
||||
FROM golang:1.23 AS builder
|
||||
ARG BUILD=now
|
||||
ARG VERSION=dev
|
||||
ARG REPO=repository
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
FROM golang:1.21 as builder
|
||||
FROM golang:1.23 AS builder
|
||||
ARG BUILD=now
|
||||
ARG VERSION=dev
|
||||
ARG REPO=repository
|
||||
|
|
Before Width: | Height: | Size: 5.5 KiB After Width: | Height: | Size: 5.5 KiB |
|
@ -1,6 +1,10 @@
|
|||
name: Build
|
||||
|
||||
on: [pull_request]
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
|
||||
jobs:
|
||||
build:
|
||||
|
@ -8,7 +12,7 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
go_versions: [ '1.20', '1.21' ]
|
||||
go_versions: [ '1.22', '1.23' ]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
|
|
@ -13,9 +13,9 @@ jobs:
|
|||
- name: Setup Go
|
||||
uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version: '1.21'
|
||||
go-version: '1.22'
|
||||
|
||||
- name: Run commit format checker
|
||||
uses: https://git.frostfs.info/TrueCloudLab/dco-go@v2
|
||||
uses: https://git.frostfs.info/TrueCloudLab/dco-go@v3
|
||||
with:
|
||||
from: 'origin/${{ github.event.pull_request.base.ref }}'
|
||||
|
|
30
.forgejo/workflows/pre-commit.yml
Normal file
30
.forgejo/workflows/pre-commit.yml
Normal file
|
@ -0,0 +1,30 @@
|
|||
name: Pre-commit hooks
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
|
||||
jobs:
|
||||
precommit:
|
||||
name: Pre-commit
|
||||
env:
|
||||
# Skip pre-commit hooks which are executed by other actions.
|
||||
SKIP: make-lint,go-staticcheck-repo-mod,go-unit-tests,gofumpt
|
||||
runs-on: ubuntu-22.04
|
||||
# If we use actions/setup-python from either Github or Gitea,
|
||||
# the line above fails with a cryptic error about not being able to find python.
|
||||
# So install everything manually.
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version: 1.23
|
||||
- name: Set up Python
|
||||
run: |
|
||||
apt update
|
||||
apt install -y pre-commit
|
||||
- name: Run pre-commit
|
||||
run: pre-commit run --color=always --hook-stage manual --all-files
|
|
@ -1,5 +1,10 @@
|
|||
name: Tests and linters
|
||||
on: [pull_request]
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
|
@ -11,7 +16,7 @@ jobs:
|
|||
- name: Set up Go
|
||||
uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version: '1.21'
|
||||
go-version: '1.23'
|
||||
cache: true
|
||||
|
||||
- name: Install linters
|
||||
|
@ -25,7 +30,7 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
go_versions: [ '1.20', '1.21' ]
|
||||
go_versions: [ '1.22', '1.23' ]
|
||||
fail-fast: false
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
@ -48,7 +53,7 @@ jobs:
|
|||
- name: Set up Go
|
||||
uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version: '1.21'
|
||||
go-version: '1.22'
|
||||
cache: true
|
||||
|
||||
- name: Run tests
|
||||
|
@ -63,7 +68,7 @@ jobs:
|
|||
- name: Set up Go
|
||||
uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version: '1.21'
|
||||
go-version: '1.23'
|
||||
cache: true
|
||||
|
||||
- name: Install staticcheck
|
||||
|
@ -71,3 +76,41 @@ jobs:
|
|||
|
||||
- name: Run staticcheck
|
||||
run: make staticcheck-run
|
||||
|
||||
gopls:
|
||||
name: gopls check
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version: '1.22'
|
||||
cache: true
|
||||
|
||||
- name: Install gopls
|
||||
run: make gopls-install
|
||||
|
||||
- name: Run gopls
|
||||
run: make gopls-run
|
||||
|
||||
fumpt:
|
||||
name: Run gofumpt
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version: '1.23'
|
||||
cache: true
|
||||
|
||||
- name: Install gofumpt
|
||||
run: make fumpt-install
|
||||
|
||||
- name: Run gofumpt
|
||||
run: |
|
||||
make fumpt
|
||||
git diff --exit-code --quiet
|
||||
|
|
|
@ -1,5 +1,10 @@
|
|||
name: Vulncheck
|
||||
on: [pull_request]
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
|
||||
jobs:
|
||||
vulncheck:
|
||||
|
@ -13,7 +18,7 @@ jobs:
|
|||
- name: Setup Go
|
||||
uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version: '1.21'
|
||||
go-version: '1.23'
|
||||
|
||||
- name: Install govulncheck
|
||||
run: go install golang.org/x/vuln/cmd/govulncheck@latest
|
||||
|
|
11
.gitlint
11
.gitlint
|
@ -1,11 +0,0 @@
|
|||
[general]
|
||||
fail-without-commits=True
|
||||
regex-style-search=True
|
||||
contrib=CC1
|
||||
|
||||
[title-match-regex]
|
||||
regex=^\[\#[0-9Xx]+\]\s
|
||||
|
||||
[ignore-by-title]
|
||||
regex=^Release(.*)
|
||||
ignore=title-match-regex
|
|
@ -12,7 +12,8 @@ run:
|
|||
# output configuration options
|
||||
output:
|
||||
# colored-line-number|line-number|json|tab|checkstyle|code-climate, default is "colored-line-number"
|
||||
format: tab
|
||||
formats:
|
||||
- format: tab
|
||||
|
||||
# all available settings of specific linters
|
||||
linters-settings:
|
||||
|
@ -37,6 +38,10 @@ linters-settings:
|
|||
alias:
|
||||
pkg: git.frostfs.info/TrueCloudLab/frostfs-sdk-go/object
|
||||
alias: objectSDK
|
||||
unused:
|
||||
field-writes-are-uses: false
|
||||
exported-fields-are-used: false
|
||||
local-variables-are-used: false
|
||||
custom:
|
||||
truecloudlab-linters:
|
||||
path: bin/linters/external_linters.so
|
||||
|
@ -66,7 +71,7 @@ linters:
|
|||
- bidichk
|
||||
- durationcheck
|
||||
- exhaustive
|
||||
- exportloopref
|
||||
- copyloopvar
|
||||
- gofmt
|
||||
- goimports
|
||||
- misspell
|
||||
|
@ -82,5 +87,7 @@ linters:
|
|||
- perfsprint
|
||||
- testifylint
|
||||
- protogetter
|
||||
- intrange
|
||||
- tenv
|
||||
disable-all: true
|
||||
fast: false
|
||||
|
|
|
@ -2,13 +2,6 @@ ci:
|
|||
autofix_prs: false
|
||||
|
||||
repos:
|
||||
- repo: https://github.com/jorisroovers/gitlint
|
||||
rev: v0.19.1
|
||||
hooks:
|
||||
- id: gitlint
|
||||
stages: [commit-msg]
|
||||
- id: gitlint-ci
|
||||
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v4.5.0
|
||||
hooks:
|
||||
|
@ -23,7 +16,7 @@ repos:
|
|||
- id: trailing-whitespace
|
||||
args: [--markdown-linebreak-ext=md]
|
||||
- id: end-of-file-fixer
|
||||
exclude: ".key$"
|
||||
exclude: "(.key|.svg)$"
|
||||
|
||||
- repo: https://github.com/shellcheck-py/shellcheck-py
|
||||
rev: v0.9.0.6
|
||||
|
@ -42,7 +35,7 @@ repos:
|
|||
hooks:
|
||||
- id: go-unit-tests
|
||||
name: go unit tests
|
||||
entry: make test
|
||||
entry: make test GOFLAGS=''
|
||||
pass_filenames: false
|
||||
types: [go]
|
||||
language: system
|
||||
|
|
|
@ -1,11 +0,0 @@
|
|||
pipeline:
|
||||
# Kludge for non-root containers under WoodPecker
|
||||
fix-ownership:
|
||||
image: alpine:latest
|
||||
commands: chown -R 1234:1234 .
|
||||
|
||||
pre-commit:
|
||||
image: git.frostfs.info/truecloudlab/frostfs-ci:v0.36
|
||||
commands:
|
||||
- export HOME="$(getent passwd $(id -u) | cut '-d:' -f6)"
|
||||
- pre-commit run --hook-stage manual
|
123
CHANGELOG.md
123
CHANGELOG.md
|
@ -3,6 +3,129 @@ Changelog for FrostFS Node
|
|||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
### Changed
|
||||
### Fixed
|
||||
### Removed
|
||||
### Updated
|
||||
|
||||
## [v0.44.0] - 2024-25-11 - Rongbuk
|
||||
|
||||
### Added
|
||||
- Allow to prioritize nodes during GET traversal via attributes (#1439)
|
||||
- Add metrics for the frostfsid cache (#1464)
|
||||
- Customize constant attributes attached to every tracing span (#1488)
|
||||
- Manage additional keys in the `frostfsid` contract (#1505)
|
||||
- Describe `--rule` flag in detail for `frostfs-cli ape-manager` subcommands (#1519)
|
||||
|
||||
### Changed
|
||||
- Support richer interaction with the console in `frostfs-cli container policy-playground` (#1396)
|
||||
- Print address in base58 format in `frostfs-adm morph policy set-admin` (#1515)
|
||||
|
||||
### Fixed
|
||||
- Fix EC object search (#1408)
|
||||
- Fix EC object put when one of the nodes is unavailable (#1427)
|
||||
|
||||
### Removed
|
||||
- Drop most of the eACL-related code (#1425)
|
||||
- Remove `--basic-acl` flag from `frostfs-cli container create` (#1483)
|
||||
|
||||
### Upgrading from v0.43.0
|
||||
The metabase schema has changed completely, resync is required.
|
||||
|
||||
## [v0.42.0]
|
||||
|
||||
### Added
|
||||
- Add audit logs for gRPC requests (#1184)
|
||||
- Add CLI command to convert eACL to APE (#1189)
|
||||
- Add `--await` flag to `control set-status` (#60)
|
||||
- `app_info` metric for binary version (#1154)
|
||||
- `--quiet` flag for healthcheck command (#1209)
|
||||
|
||||
### Changed
|
||||
- Deprecate Container.SetEACL RPC (#1219)
|
||||
|
||||
### Fixed
|
||||
- Take groups into account during APE processing (#1190)
|
||||
- Handle double SIGHUP correctly (#1145)
|
||||
- Handle empty filenames in tree listing (#1074)
|
||||
- Handle duplicate tree nodes in the split-brain scenario (#1234, #1251)
|
||||
- Remove APE pre-check in Object.GET/HEAD/RANGE RPC (#1249)
|
||||
- Delete EC gc marks and split info (#1257)
|
||||
- Do not search for non-existent objects on deletion (#1261)
|
||||
|
||||
### Updated
|
||||
- Make putting EC chunks more robust (#1233)
|
||||
|
||||
## [v0.41.0]
|
||||
|
||||
### Added
|
||||
- Support mTLS for morph client (#1170)
|
||||
|
||||
### Fixed
|
||||
- Update shard state metric during shard init (#1174)
|
||||
- Handle ENOSPC in blobovnicza (#1166)
|
||||
- Handle multiple split-infos for EC objects (#1163)
|
||||
- Set `Disabled` mode as the default for components (#1168)
|
||||
|
||||
## [v0.40.0]
|
||||
|
||||
### Added
|
||||
- Support EC chunk reconstruction in policer (#1129)
|
||||
- Support LOCK, DELETE and SEARCH methods on EC objects (#1147, 1144)
|
||||
- apemanager service to manage APE chains (#1105)
|
||||
|
||||
### Fixed
|
||||
- Properly verify GetRangeHash response (#1083)
|
||||
- Send `MONOTONIC_USEC` in sdnotify on reload (#1135)
|
||||
|
||||
### Updated
|
||||
- neo-go to `v0.106.0`
|
||||
|
||||
## [v0.39.0]
|
||||
|
||||
### Added
|
||||
- Preliminary erasure coding support (#1065, #1112, #1103, #1120)
|
||||
- TTL cache for blobovnicza tree (#1004)
|
||||
- Cache for frostfsid and policy contracts (#1117)
|
||||
- Writecache path to metric labels (#966)
|
||||
- Documentation for authentication mechanisms (#1097, #1104)
|
||||
- Metrics for metabase resync status (#1029)
|
||||
|
||||
### Changed
|
||||
- Speed up metabase resync (#1024)
|
||||
|
||||
### Fixed
|
||||
- Possible panic in GET_RANGE (#1077)
|
||||
|
||||
### Updated
|
||||
- Minimum required Go version to 1.21
|
||||
|
||||
## [v0.38.0]
|
||||
|
||||
### Added
|
||||
- Add `trace_id` to logs in `frostfs-node` (#146)
|
||||
- Allow to forcefully remove container from IR (#733)
|
||||
- LOKI support (#740)
|
||||
- Allow sealing writecache (#569)
|
||||
- Support tree service in data evacuation (#947)
|
||||
- Use new policy engine mechanism for access control (#770, #804)
|
||||
- Log about active notary deposit waiting (#963)
|
||||
|
||||
### Changed
|
||||
- Sort output in `frostfs-cli` subcommands (#333)
|
||||
- Send bootstrap query at each epoch tick (#721)
|
||||
- Do not retain garbage in fstree on systems supporting O_TMPFILE (#970)
|
||||
|
||||
### Fixed
|
||||
- Handle synchronization failures better in tree service (#741)
|
||||
- Fix invalid batch size for iterator traversal in morph (#1000)
|
||||
|
||||
### Updated
|
||||
- `neo-go` to `v0.105.0`
|
||||
|
||||
## [v0.37.0]
|
||||
|
||||
### Added
|
||||
- Support impersonate bearer token (#229)
|
||||
- Change log level on SIGHUP for ir (#125)
|
||||
|
|
3
CODEOWNERS
Normal file
3
CODEOWNERS
Normal file
|
@ -0,0 +1,3 @@
|
|||
.* @TrueCloudLab/storage-core-committers @TrueCloudLab/storage-core-developers
|
||||
.forgejo/.* @potyarkin
|
||||
Makefile @potyarkin
|
115
Makefile
115
Makefile
|
@ -4,20 +4,19 @@ SHELL = bash
|
|||
REPO ?= $(shell go list -m)
|
||||
VERSION ?= $(shell git describe --tags --dirty --match "v*" --always --abbrev=8 2>/dev/null || cat VERSION 2>/dev/null || echo "develop")
|
||||
|
||||
HUB_IMAGE ?= truecloudlab/frostfs
|
||||
HUB_IMAGE ?= git.frostfs.info/truecloudlab/frostfs
|
||||
HUB_TAG ?= "$(shell echo ${VERSION} | sed 's/^v//')"
|
||||
|
||||
GO_VERSION ?= 1.21
|
||||
LINT_VERSION ?= 1.55.2
|
||||
TRUECLOUDLAB_LINT_VERSION ?= 0.0.3
|
||||
GO_VERSION ?= 1.22
|
||||
LINT_VERSION ?= 1.62.0
|
||||
TRUECLOUDLAB_LINT_VERSION ?= 0.0.8
|
||||
PROTOC_VERSION ?= 25.0
|
||||
PROTOC_GEN_GO_VERSION ?= $(shell go list -f '{{.Version}}' -m google.golang.org/protobuf)
|
||||
PROTOGEN_FROSTFS_VERSION ?= $(shell go list -f '{{.Version}}' -m git.frostfs.info/TrueCloudLab/frostfs-api-go/v2)
|
||||
PROTOGEN_FROSTFS_VERSION ?= $(shell go list -f '{{.Version}}' -m git.frostfs.info/TrueCloudLab/frostfs-sdk-go)
|
||||
PROTOC_OS_VERSION=osx-x86_64
|
||||
ifeq ($(shell uname), Linux)
|
||||
PROTOC_OS_VERSION=linux-x86_64
|
||||
endif
|
||||
STATICCHECK_VERSION ?= 2023.1.6
|
||||
STATICCHECK_VERSION ?= 2024.1.1
|
||||
ARCH = amd64
|
||||
|
||||
BIN = bin
|
||||
|
@ -28,28 +27,32 @@ DIRS = $(BIN) $(RELEASE)
|
|||
CMDS = $(notdir $(basename $(wildcard cmd/frostfs-*)))
|
||||
BINS = $(addprefix $(BIN)/, $(CMDS))
|
||||
|
||||
# .deb package versioning
|
||||
OS_RELEASE = $(shell lsb_release -cs)
|
||||
PKG_VERSION ?= $(shell echo $(VERSION) | sed "s/^v//" | \
|
||||
sed -E "s/(.*)-(g[a-fA-F0-9]{6,8})(.*)/\1\3~\2/" | \
|
||||
sed "s/-/~/")-${OS_RELEASE}
|
||||
|
||||
OUTPUT_LINT_DIR ?= $(abspath $(BIN))/linters
|
||||
LINT_DIR = $(OUTPUT_LINT_DIR)/golangci-lint-$(LINT_VERSION)-v$(TRUECLOUDLAB_LINT_VERSION)
|
||||
TMP_DIR := .cache
|
||||
PROTOBUF_DIR ?= $(abspath $(BIN))/protobuf
|
||||
PROTOC_DIR ?= $(PROTOBUF_DIR)/protoc-v$(PROTOC_VERSION)
|
||||
PROTOC_GEN_GO_DIR ?= $(PROTOBUF_DIR)/protoc-gen-go-$(PROTOC_GEN_GO_VERSION)
|
||||
PROTOGEN_FROSTFS_DIR ?= $(PROTOBUF_DIR)/protogen-$(PROTOGEN_FROSTFS_VERSION)
|
||||
STATICCHECK_DIR ?= $(abspath $(BIN))/staticcheck
|
||||
STATICCHECK_VERSION_DIR ?= $(STATICCHECK_DIR)/$(STATICCHECK_VERSION)
|
||||
|
||||
SOURCES = $(shell find . -type f -name "*.go" -print)
|
||||
|
||||
GOFUMPT_VERSION ?= v0.7.0
|
||||
GOFUMPT_DIR ?= $(abspath $(BIN))/gofumpt
|
||||
GOFUMPT_VERSION_DIR ?= $(GOFUMPT_DIR)/$(GOFUMPT_VERSION)
|
||||
|
||||
GOPLS_VERSION ?= v0.15.1
|
||||
GOPLS_DIR ?= $(abspath $(BIN))/gopls
|
||||
GOPLS_VERSION_DIR ?= $(GOPLS_DIR)/$(GOPLS_VERSION)
|
||||
GOPLS_TEMP_FILE := $(shell mktemp)
|
||||
|
||||
FROSTFS_CONTRACTS_PATH=$(abspath ./../frostfs-contract)
|
||||
LOCODE_DB_PATH=$(abspath ./.cache/locode_db)
|
||||
LOCODE_DB_VERSION=v0.4.0
|
||||
|
||||
.PHONY: help all images dep clean fmts fumpt imports test lint docker/lint
|
||||
prepare-release debpackage pre-commit unpre-commit
|
||||
prepare-release pre-commit unpre-commit
|
||||
|
||||
# To build a specific binary, use it's name prefix with bin/ as a target
|
||||
# For example `make bin/frostfs-node` will build only storage node binary
|
||||
|
@ -96,21 +99,20 @@ export-metrics: dep
|
|||
|
||||
# Regenerate proto files:
|
||||
protoc:
|
||||
@if [ ! -d "$(PROTOC_DIR)" ] || [ ! -d "$(PROTOC_GEN_GO_DIR)" ] || [ ! -d "$(PROTOGEN_FROSTFS_DIR)" ]; then \
|
||||
@if [ ! -d "$(PROTOC_DIR)" ] || [ ! -d "$(PROTOGEN_FROSTFS_DIR)" ]; then \
|
||||
make protoc-install; \
|
||||
fi
|
||||
@for f in `find . -type f -name '*.proto' -not -path './bin/*'`; do \
|
||||
echo "⇒ Processing $$f "; \
|
||||
$(PROTOC_DIR)/bin/protoc \
|
||||
--proto_path=.:$(PROTOC_DIR)/include:/usr/local/include \
|
||||
--plugin=protoc-gen-go=$(PROTOC_GEN_GO_DIR)/protoc-gen-go \
|
||||
--plugin=protoc-gen-go-frostfs=$(PROTOGEN_FROSTFS_DIR)/protogen \
|
||||
--go-frostfs_out=. --go-frostfs_opt=paths=source_relative \
|
||||
--go_out=. --go_opt=paths=source_relative \
|
||||
--go-grpc_opt=require_unimplemented_servers=false \
|
||||
--go-grpc_out=. --go-grpc_opt=paths=source_relative $$f; \
|
||||
done
|
||||
|
||||
# Install protoc
|
||||
protoc-install:
|
||||
@rm -rf $(PROTOBUF_DIR)
|
||||
@mkdir $(PROTOBUF_DIR)
|
||||
|
@ -118,10 +120,8 @@ protoc-install:
|
|||
@wget -q -O $(PROTOBUF_DIR)/protoc-$(PROTOC_VERSION).zip 'https://github.com/protocolbuffers/protobuf/releases/download/v$(PROTOC_VERSION)/protoc-$(PROTOC_VERSION)-$(PROTOC_OS_VERSION).zip'
|
||||
@unzip -q -o $(PROTOBUF_DIR)/protoc-$(PROTOC_VERSION).zip -d $(PROTOC_DIR)
|
||||
@rm $(PROTOBUF_DIR)/protoc-$(PROTOC_VERSION).zip
|
||||
@echo "⇒ Installing protoc-gen-go..."
|
||||
@GOBIN=$(PROTOC_GEN_GO_DIR) go install -v google.golang.org/protobuf/...@$(PROTOC_GEN_GO_VERSION)
|
||||
@echo "⇒ Instaling protogen FrostFS plugin..."
|
||||
@GOBIN=$(PROTOGEN_FROSTFS_DIR) go install -mod=mod -v git.frostfs.info/TrueCloudLab/frostfs-api-go/v2/util/protogen@$(PROTOGEN_FROSTFS_VERSION)
|
||||
@GOBIN=$(PROTOGEN_FROSTFS_DIR) go install -mod=mod -v git.frostfs.info/TrueCloudLab/frostfs-sdk-go/api/util/protogen@$(PROTOGEN_FROSTFS_VERSION)
|
||||
|
||||
# Build FrostFS component's docker image
|
||||
image-%:
|
||||
|
@ -157,15 +157,27 @@ imports:
|
|||
@echo "⇒ Processing goimports check"
|
||||
@goimports -w cmd/ pkg/ misc/
|
||||
|
||||
# Install gofumpt
|
||||
fumpt-install:
|
||||
@rm -rf $(GOFUMPT_DIR)
|
||||
@mkdir $(GOFUMPT_DIR)
|
||||
@GOBIN=$(GOFUMPT_VERSION_DIR) go install mvdan.cc/gofumpt@$(GOFUMPT_VERSION)
|
||||
|
||||
# Run gofumpt
|
||||
fumpt:
|
||||
@if [ ! -d "$(GOFUMPT_VERSION_DIR)" ]; then \
|
||||
make fumpt-install; \
|
||||
fi
|
||||
@echo "⇒ Processing gofumpt check"
|
||||
@gofumpt -l -w cmd/ pkg/ misc/
|
||||
$(GOFUMPT_VERSION_DIR)/gofumpt -l -w cmd/ pkg/ misc/
|
||||
|
||||
# Run Unit Test with go test
|
||||
test: GOFLAGS ?= "-count=1"
|
||||
test:
|
||||
@echo "⇒ Running go test"
|
||||
@go test ./... -count=1
|
||||
@GOFLAGS="$(GOFLAGS)" go test ./...
|
||||
|
||||
# Run pre-commit
|
||||
pre-commit-run:
|
||||
@pre-commit run -a --hook-stage manual
|
||||
|
||||
|
@ -179,7 +191,7 @@ lint-install:
|
|||
@@make -C $(TMP_DIR)/linters lib CGO_ENABLED=1 OUT_DIR=$(OUTPUT_LINT_DIR)
|
||||
@rm -rf $(TMP_DIR)/linters
|
||||
@rmdir $(TMP_DIR) 2>/dev/null || true
|
||||
@CGO_ENABLED=1 GOBIN=$(LINT_DIR) go install github.com/golangci/golangci-lint/cmd/golangci-lint@v$(LINT_VERSION)
|
||||
@CGO_ENABLED=1 GOBIN=$(LINT_DIR) go install -trimpath github.com/golangci/golangci-lint/cmd/golangci-lint@v$(LINT_VERSION)
|
||||
|
||||
# Run linters
|
||||
lint:
|
||||
|
@ -201,6 +213,24 @@ staticcheck-run:
|
|||
fi
|
||||
@$(STATICCHECK_VERSION_DIR)/staticcheck ./...
|
||||
|
||||
# Install gopls
|
||||
gopls-install:
|
||||
@rm -rf $(GOPLS_DIR)
|
||||
@mkdir $(GOPLS_DIR)
|
||||
@GOBIN=$(GOPLS_VERSION_DIR) go install golang.org/x/tools/gopls@$(GOPLS_VERSION)
|
||||
|
||||
# Run gopls
|
||||
gopls-run:
|
||||
@if [ ! -d "$(GOPLS_VERSION_DIR)" ]; then \
|
||||
make gopls-install; \
|
||||
fi
|
||||
$(GOPLS_VERSION_DIR)/gopls check $(SOURCES) 2>&1 >$(GOPLS_TEMP_FILE)
|
||||
@if [[ $$(wc -l < $(GOPLS_TEMP_FILE)) -ne 0 ]]; then \
|
||||
cat $(GOPLS_TEMP_FILE); \
|
||||
exit 1; \
|
||||
fi
|
||||
rm $(GOPLS_TEMP_FILE)
|
||||
|
||||
# Run linters in Docker
|
||||
docker/lint:
|
||||
docker run --rm -t \
|
||||
|
@ -227,36 +257,33 @@ clean:
|
|||
rm -rf $(BIN)
|
||||
rm -rf $(RELEASE)
|
||||
|
||||
# Package for Debian
|
||||
debpackage:
|
||||
dch -b --package frostfs-node \
|
||||
--controlmaint \
|
||||
--newversion $(PKG_VERSION) \
|
||||
--distribution $(OS_RELEASE) \
|
||||
"Please see CHANGELOG.md for code changes for $(VERSION)"
|
||||
dpkg-buildpackage --no-sign -b
|
||||
|
||||
debclean:
|
||||
dh clean
|
||||
|
||||
# Download locode database
|
||||
locode-download:
|
||||
@wget -q -O ./.cache/locode_db.gz 'https://git.frostfs.info/TrueCloudLab/frostfs-locode-db/releases/download/${LOCODE_DB_VERSION}/locode_db.gz'
|
||||
gzip -dfk ./.cache/locode_db.gz
|
||||
mkdir -p $(TMP_DIR)
|
||||
@wget -q -O ./$(TMP_DIR)/locode_db.gz 'https://git.frostfs.info/TrueCloudLab/frostfs-locode-db/releases/download/${LOCODE_DB_VERSION}/locode_db.gz'
|
||||
gzip -dfk ./$(TMP_DIR)/locode_db.gz
|
||||
|
||||
# Start dev environment
|
||||
env-up: all
|
||||
docker compose -f dev/docker-compose.yml up -d
|
||||
@if [ ! -d "$(FROSTFS_CONTRACTS_PATH)" ]; then \
|
||||
echo "Frostfs contracts not found"; exit 1; \
|
||||
fi
|
||||
${BIN}/frostfs-adm --config ./dev/adm/frostfs-adm.yml morph init --contracts ${FROSTFS_CONTRACTS_PATH}
|
||||
${BIN}/frostfs-adm --config ./dev/adm/frostfs-adm.yml morph refill-gas --storage-wallet ./dev/storage/wallet.json --gas 10.0
|
||||
${BIN}/frostfs-adm --config ./dev/adm/frostfs-adm.yml morph refill-gas --gas 10.0 \
|
||||
--storage-wallet ./dev/storage/wallet01.json \
|
||||
--storage-wallet ./dev/storage/wallet02.json \
|
||||
--storage-wallet ./dev/storage/wallet03.json \
|
||||
--storage-wallet ./dev/storage/wallet04.json
|
||||
|
||||
@if [ ! -f "$(LOCODE_DB_PATH)" ]; then \
|
||||
make locode-download; \
|
||||
fi
|
||||
mkdir -p ./$(TMP_DIR)/state
|
||||
mkdir -p ./$(TMP_DIR)/storage
|
||||
|
||||
# Shutdown dev environment
|
||||
env-down:
|
||||
docker compose -f dev/docker-compose.yml down
|
||||
docker volume rm -f frostfs-node_neo-go
|
||||
rm -f ./.cache/.frostfs-ir-state
|
||||
rm -f ./.cache/.frostfs-node-state
|
||||
rm -rf ./.cache/storage
|
||||
docker compose -f dev/docker-compose.yml down -v
|
||||
rm -rf ./$(TMP_DIR)/state
|
||||
rm -rf ./$(TMP_DIR)/storage
|
||||
|
|
23
README.md
23
README.md
|
@ -1,5 +1,5 @@
|
|||
<p align="center">
|
||||
<img src="./.github/logo.svg" width="500px" alt="FrostFS">
|
||||
<img src="./.forgejo/logo.svg" width="500px" alt="FrostFS">
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
|
@ -7,9 +7,8 @@
|
|||
</p>
|
||||
|
||||
---
|
||||
[![Report](https://goreportcard.com/badge/github.com/TrueCloudLab/frostfs-node)](https://goreportcard.com/report/github.com/TrueCloudLab/frostfs-node)
|
||||
![GitHub release (latest SemVer)](https://img.shields.io/github/v/release/TrueCloudLab/frostfs-node?sort=semver)
|
||||
![License](https://img.shields.io/github/license/TrueCloudLab/frostfs-node.svg?style=popout)
|
||||
[![Report](https://goreportcard.com/badge/git.frostfs.info/TrueCloudLab/frostfs-node)](https://goreportcard.com/report/git.frostfs.info/TrueCloudLab/frostfs-node)
|
||||
![Release (latest)](https://git.frostfs.info/TrueCloudLab/frostfs-node/badges/release.svg)
|
||||
|
||||
# Overview
|
||||
|
||||
|
@ -33,8 +32,8 @@ manipulate large amounts of data without paying a prohibitive price.
|
|||
|
||||
FrostFS has a native [gRPC API](https://git.frostfs.info/TrueCloudLab/frostfs-api) and has
|
||||
protocol gateways for popular protocols such as [AWS
|
||||
S3](https://github.com/TrueCloudLab/frostfs-s3-gw),
|
||||
[HTTP](https://github.com/TrueCloudLab/frostfs-http-gw),
|
||||
S3](https://git.frostfs.info/TrueCloudLab/frostfs-s3-gw),
|
||||
[HTTP](https://git.frostfs.info/TrueCloudLab/frostfs-http-gw),
|
||||
[FUSE](https://wikipedia.org/wiki/Filesystem_in_Userspace) and
|
||||
[sFTP](https://en.wikipedia.org/wiki/SSH_File_Transfer_Protocol) allowing
|
||||
developers to integrate applications without rewriting their code.
|
||||
|
@ -45,11 +44,11 @@ Now, we only support GNU/Linux on amd64 CPUs with AVX/AVX2 instructions. More
|
|||
platforms will be officially supported after release `1.0`.
|
||||
|
||||
The latest version of frostfs-node works with frostfs-contract
|
||||
[v0.16.0](https://github.com/TrueCloudLab/frostfs-contract/releases/tag/v0.16.0).
|
||||
[v0.19.2](https://git.frostfs.info/TrueCloudLab/frostfs-contract/releases/tag/v0.19.2).
|
||||
|
||||
# Building
|
||||
|
||||
To make all binaries you need Go 1.20+ and `make`:
|
||||
To make all binaries you need Go 1.22+ and `make`:
|
||||
```
|
||||
make all
|
||||
```
|
||||
|
@ -71,7 +70,7 @@ make docker/bin/frostfs-<name> # build a specific binary
|
|||
|
||||
## Docker images
|
||||
|
||||
To make docker images suitable for use in [frostfs-dev-env](https://github.com/TrueCloudLab/frostfs-dev-env/) use:
|
||||
To make docker images suitable for use in [frostfs-dev-env](https://git.frostfs.info/TrueCloudLab/frostfs-dev-env/) use:
|
||||
```
|
||||
make images
|
||||
```
|
||||
|
@ -99,12 +98,12 @@ See `frostfs-contract`'s README.md for build instructions.
|
|||
4. To create container and put object into it run (container and object IDs will be different):
|
||||
|
||||
```
|
||||
./bin/frostfs-cli container create -r 127.0.0.1:8080 --wallet ./dev/wallet.json --policy "REP 1 IN X CBF 1 SELECT 1 FROM * AS X" --basic-acl public-read-write --await
|
||||
./bin/frostfs-cli container create -r 127.0.0.1:8080 --wallet ./dev/wallet.json --policy "REP 1 IN X CBF 1 SELECT 1 FROM * AS X" --await
|
||||
Enter password > <- press ENTER, the is no password for wallet
|
||||
CID: CfPhEuHQ2PRvM4gfBQDC4dWZY3NccovyfcnEdiq2ixju
|
||||
|
||||
./bin/frostfs-cli object put -r 127.0.0.1:8080 --wallet ./dev/wallet.json --file README.md --cid CfPhEuHQ2PRvM4gfBQDC4dWZY3NccovyfcnEdiq2ixju
|
||||
Enter password >
|
||||
Enter password >
|
||||
4300 / 4300 [===========================================================================================================================================================================================================] 100.00% 0s
|
||||
[README.md] Object successfully stored
|
||||
OID: 78sohnudVMnPsczXqsTUcvezosan2YDNVZwDE8Kq5YwU
|
||||
|
@ -125,7 +124,7 @@ the feature/topic you are going to implement.
|
|||
|
||||
# Credits
|
||||
|
||||
FrostFS is maintained by [True Cloud Lab](https://github.com/TrueCloudLab/) with the help and
|
||||
FrostFS is maintained by [True Cloud Lab](https://git.frostfs.info/TrueCloudLab/) with the help and
|
||||
contributions from community members.
|
||||
|
||||
Please see [CREDITS](CREDITS.md) for details.
|
||||
|
|
2
VERSION
2
VERSION
|
@ -1 +1 @@
|
|||
v0.36.0
|
||||
v0.44.0
|
||||
|
|
|
@ -56,7 +56,8 @@ credentials: # passwords for consensus node / alphabet wallets
|
|||
#### Network deployment
|
||||
|
||||
- `generate-alphabet` generates a set of wallets for consensus and
|
||||
Alphabet nodes.
|
||||
Alphabet nodes. The list of the name for alphabet wallets(no gaps between names allowed, order is important):
|
||||
- az, buky, vedi, glagoli, dobro, yest, zhivete, dzelo, zemlja, izhe, izhei, gerv, kako, ljudi, mislete, nash, on, pokoj, rtsi, slovo, tverdo, uk
|
||||
|
||||
- `init` initializes the sidechain by deploying smart contracts and
|
||||
setting provided FrostFS network configuration.
|
||||
|
|
|
@ -9,8 +9,8 @@ related configuration details.
|
|||
|
||||
To follow this guide you need:
|
||||
- latest released version of [neo-go](https://github.com/nspcc-dev/neo-go/releases) (v0.97.2 at the moment),
|
||||
- latest released version of [frostfs-adm](https://github.com/TrueCloudLab/frostfs-node/releases) utility (v0.25.1 at the moment),
|
||||
- latest released version of compiled [frostfs-contract](https://github.com/TrueCloudLab/frostfs-contract/releases) (v0.11.0 at the moment).
|
||||
- latest released version of [frostfs-adm](https://git.frostfs.info/TrueCloudLab/frostfs-node/releases) utility (v0.42.9 at the moment),
|
||||
- latest released version of compiled [frostfs-contract](https://git.frostfs.info/TrueCloudLab/frostfs-contract/releases) (v0.19.2 at the moment).
|
||||
|
||||
## Step 1: Prepare network configuration
|
||||
|
||||
|
@ -34,6 +34,8 @@ alphabet-wallets: /home/user/deploy/alphabet-wallets
|
|||
network:
|
||||
max_object_size: 67108864
|
||||
epoch_duration: 240
|
||||
max_ec_data_count: 12
|
||||
max_ec_parity_count: 4
|
||||
fee:
|
||||
candidate: 0
|
||||
container: 0
|
||||
|
@ -62,6 +64,11 @@ alphabet-wallets: /home/user/deploy/alphabet-wallets
|
|||
wallet[0]: hunter2
|
||||
```
|
||||
|
||||
This command generates wallets with the following names:
|
||||
- az, buky, vedi, glagoli, dobro, yest, zhivete, dzelo, zemlja, izhe, izhei, gerv, kako, ljudi, mislete, nash, on, pokoj, rtsi, slovo, tverdo, uk
|
||||
|
||||
No gaps between names allowed, order is important.
|
||||
|
||||
Do not lose wallet files and network config. Store it in an encrypted backed up
|
||||
storage.
|
||||
|
||||
|
|
|
@ -11,4 +11,33 @@ const (
|
|||
Verbose = "verbose"
|
||||
VerboseShorthand = "v"
|
||||
VerboseUsage = "Verbose output"
|
||||
|
||||
EndpointFlag = "rpc-endpoint"
|
||||
EndpointFlagDesc = "N3 RPC node endpoint"
|
||||
EndpointFlagShort = "r"
|
||||
|
||||
AlphabetWalletsFlag = "alphabet-wallets"
|
||||
AlphabetWalletsFlagDesc = "Path to alphabet wallets dir"
|
||||
|
||||
LocalDumpFlag = "local-dump"
|
||||
ProtoConfigPath = "protocol"
|
||||
ContractsInitFlag = "contracts"
|
||||
ContractsInitFlagDesc = "Path to archive with compiled FrostFS contracts (the default is to fetch the latest release from the official repository)"
|
||||
ContractsURLFlag = "contracts-url"
|
||||
ContractsURLFlagDesc = "URL to archive with compiled FrostFS contracts"
|
||||
EpochDurationInitFlag = "network.epoch_duration"
|
||||
MaxObjectSizeInitFlag = "network.max_object_size"
|
||||
MaxECDataCountFlag = "network.max_ec_data_count"
|
||||
MaxECParityCounFlag = "network.max_ec_parity_count"
|
||||
RefillGasAmountFlag = "gas"
|
||||
StorageWalletFlag = "storage-wallet"
|
||||
ContainerFeeInitFlag = "network.fee.container"
|
||||
ContainerAliasFeeInitFlag = "network.fee.container_alias"
|
||||
CandidateFeeInitFlag = "network.fee.candidate"
|
||||
WithdrawFeeInitFlag = "network.fee.withdraw"
|
||||
MaintenanceModeAllowedInitFlag = "network.maintenance_mode_allowed"
|
||||
HomomorphicHashDisabledInitFlag = "network.homomorphic_hash_disabled"
|
||||
CustomZoneFlag = "domain"
|
||||
AlphabetSizeFlag = "size"
|
||||
AllFlag = "all"
|
||||
)
|
||||
|
|
|
@ -21,6 +21,8 @@ type configTemplate struct {
|
|||
CandidateFee int
|
||||
ContainerFee int
|
||||
ContainerAliasFee int
|
||||
MaxECDataCount int
|
||||
MaxECParityCount int
|
||||
WithdrawFee int
|
||||
Glagolitics []string
|
||||
HomomorphicHashDisabled bool
|
||||
|
@ -31,6 +33,8 @@ alphabet-wallets: {{ .AlphabetDir}}
|
|||
network:
|
||||
max_object_size: {{ .MaxObjectSize}}
|
||||
epoch_duration: {{ .EpochDuration}}
|
||||
max_ec_data_count: {{ .MaxECDataCount}}
|
||||
max_ec_parity_count: {{ .MaxECParityCount}}
|
||||
homomorphic_hash_disabled: {{ .HomomorphicHashDisabled}}
|
||||
fee:
|
||||
candidate: {{ .CandidateFee}}
|
||||
|
@ -106,6 +110,8 @@ func generateConfigExample(appDir string, credSize int) (string, error) {
|
|||
tmpl := configTemplate{
|
||||
Endpoint: "https://neo.rpc.node:30333",
|
||||
MaxObjectSize: 67108864, // 64 MiB
|
||||
MaxECDataCount: 12, // Tested with 16-node networks, assuming 12 data + 4 parity nodes.
|
||||
MaxECParityCount: 4, // Maximum 4 parity chunks, typically <= 3 for most policies.
|
||||
EpochDuration: 240, // 1 hour with 15s per block
|
||||
HomomorphicHashDisabled: false, // object homomorphic hash is enabled
|
||||
CandidateFee: 100_0000_0000, // 100.0 GAS (Fixed8)
|
||||
|
@ -122,7 +128,7 @@ func generateConfigExample(appDir string, credSize int) (string, error) {
|
|||
tmpl.AlphabetDir = filepath.Join(appDir, "alphabet-wallets")
|
||||
|
||||
var i innerring.GlagoliticLetter
|
||||
for i = 0; i < innerring.GlagoliticLetter(credSize); i++ {
|
||||
for i = range innerring.GlagoliticLetter(credSize) {
|
||||
tmpl.Glagolitics = append(tmpl.Glagolitics, i.String())
|
||||
}
|
||||
|
||||
|
|
|
@ -27,6 +27,8 @@ func TestGenerateConfigExample(t *testing.T) {
|
|||
require.Equal(t, "https://neo.rpc.node:30333", v.GetString("rpc-endpoint"))
|
||||
require.Equal(t, filepath.Join(appDir, "alphabet-wallets"), v.GetString("alphabet-wallets"))
|
||||
require.Equal(t, 67108864, v.GetInt("network.max_object_size"))
|
||||
require.Equal(t, 12, v.GetInt("network.max_ec_data_count"))
|
||||
require.Equal(t, 4, v.GetInt("network.max_ec_parity_count"))
|
||||
require.Equal(t, 240, v.GetInt("network.epoch_duration"))
|
||||
require.Equal(t, 10000000000, v.GetInt("network.fee.candidate"))
|
||||
require.Equal(t, 1000, v.GetInt("network.fee.container"))
|
||||
|
|
15
cmd/frostfs-adm/internal/modules/metabase/root.go
Normal file
15
cmd/frostfs-adm/internal/modules/metabase/root.go
Normal file
|
@ -0,0 +1,15 @@
|
|||
package metabase
|
||||
|
||||
import "github.com/spf13/cobra"
|
||||
|
||||
// RootCmd is a root command of config section.
|
||||
var RootCmd = &cobra.Command{
|
||||
Use: "metabase",
|
||||
Short: "Section for metabase commands",
|
||||
}
|
||||
|
||||
func init() {
|
||||
RootCmd.AddCommand(UpgradeCmd)
|
||||
|
||||
initUpgradeCommand()
|
||||
}
|
150
cmd/frostfs-adm/internal/modules/metabase/upgrade.go
Normal file
150
cmd/frostfs-adm/internal/modules/metabase/upgrade.go
Normal file
|
@ -0,0 +1,150 @@
|
|||
package metabase
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-node/config"
|
||||
engineconfig "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-node/config/engine"
|
||||
shardconfig "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-node/config/engine/shard"
|
||||
morphconfig "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-node/config/morph"
|
||||
nodeconfig "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-node/config/node"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/core/container"
|
||||
meta "git.frostfs.info/TrueCloudLab/frostfs-node/pkg/local_object_storage/metabase"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/morph/client"
|
||||
morphcontainer "git.frostfs.info/TrueCloudLab/frostfs-node/pkg/morph/client/container"
|
||||
"github.com/spf13/cobra"
|
||||
"golang.org/x/sync/errgroup"
|
||||
)
|
||||
|
||||
const (
|
||||
noCompactFlag = "no-compact"
|
||||
)
|
||||
|
||||
var (
|
||||
errNoPathsFound = errors.New("no metabase paths found")
|
||||
errNoMorphEndpointsFound = errors.New("no morph endpoints found")
|
||||
)
|
||||
|
||||
var UpgradeCmd = &cobra.Command{
|
||||
Use: "upgrade",
|
||||
Short: "Upgrade metabase to latest version",
|
||||
RunE: upgrade,
|
||||
}
|
||||
|
||||
func upgrade(cmd *cobra.Command, _ []string) error {
|
||||
configFile, err := cmd.Flags().GetString(commonflags.ConfigFlag)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
configDir, err := cmd.Flags().GetString(commonflags.ConfigDirFlag)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
appCfg := config.New(configFile, configDir, config.EnvPrefix)
|
||||
paths, err := getMetabasePaths(appCfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(paths) == 0 {
|
||||
return errNoPathsFound
|
||||
}
|
||||
cmd.Println("found", len(paths), "metabases:")
|
||||
for i, path := range paths {
|
||||
cmd.Println(i+1, ":", path)
|
||||
}
|
||||
mc, err := createMorphClient(cmd.Context(), appCfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer mc.Close()
|
||||
civ, err := createContainerInfoProvider(mc)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
noCompact, _ := cmd.Flags().GetBool(noCompactFlag)
|
||||
result := make(map[string]bool)
|
||||
var resultGuard sync.Mutex
|
||||
eg, ctx := errgroup.WithContext(cmd.Context())
|
||||
for _, path := range paths {
|
||||
eg.Go(func() error {
|
||||
var success bool
|
||||
cmd.Println("upgrading metabase", path, "...")
|
||||
if err := meta.Upgrade(ctx, path, !noCompact, civ, func(a ...any) {
|
||||
cmd.Println(append([]any{time.Now().Format(time.RFC3339), ":", path, ":"}, a...)...)
|
||||
}); err != nil {
|
||||
cmd.Println("error: failed to upgrade metabase", path, ":", err)
|
||||
} else {
|
||||
success = true
|
||||
cmd.Println("metabase", path, "upgraded successfully")
|
||||
}
|
||||
resultGuard.Lock()
|
||||
result[path] = success
|
||||
resultGuard.Unlock()
|
||||
return nil
|
||||
})
|
||||
}
|
||||
if err := eg.Wait(); err != nil {
|
||||
return err
|
||||
}
|
||||
for mb, ok := range result {
|
||||
if ok {
|
||||
cmd.Println(mb, ": success")
|
||||
} else {
|
||||
cmd.Println(mb, ": failed")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func getMetabasePaths(appCfg *config.Config) ([]string, error) {
|
||||
var paths []string
|
||||
if err := engineconfig.IterateShards(appCfg, false, func(sc *shardconfig.Config) error {
|
||||
paths = append(paths, sc.Metabase().Path())
|
||||
return nil
|
||||
}); err != nil {
|
||||
return nil, fmt.Errorf("get metabase paths: %w", err)
|
||||
}
|
||||
return paths, nil
|
||||
}
|
||||
|
||||
func createMorphClient(ctx context.Context, appCfg *config.Config) (*client.Client, error) {
|
||||
addresses := morphconfig.RPCEndpoint(appCfg)
|
||||
if len(addresses) == 0 {
|
||||
return nil, errNoMorphEndpointsFound
|
||||
}
|
||||
key := nodeconfig.Key(appCfg)
|
||||
cli, err := client.New(ctx,
|
||||
key,
|
||||
client.WithDialTimeout(morphconfig.DialTimeout(appCfg)),
|
||||
client.WithEndpoints(addresses...),
|
||||
client.WithSwitchInterval(morphconfig.SwitchInterval(appCfg)),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create morph client:%w", err)
|
||||
}
|
||||
return cli, nil
|
||||
}
|
||||
|
||||
func createContainerInfoProvider(cli *client.Client) (container.InfoProvider, error) {
|
||||
sh, err := cli.NNSContractAddress(client.NNSContainerContractName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("resolve container contract hash: %w", err)
|
||||
}
|
||||
cc, err := morphcontainer.NewFromMorph(cli, sh, 0)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create morph container client: %w", err)
|
||||
}
|
||||
return container.NewInfoProvider(func() (container.Source, error) {
|
||||
return morphcontainer.AsContainerSource(cc), nil
|
||||
}), nil
|
||||
}
|
||||
|
||||
func initUpgradeCommand() {
|
||||
flags := UpgradeCmd.Flags()
|
||||
flags.Bool(noCompactFlag, false, "Do not compact upgraded metabase file")
|
||||
}
|
|
@ -1,220 +0,0 @@
|
|||
package morph
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
|
||||
parseutil "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-cli/modules/util"
|
||||
commonCmd "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/internal/common"
|
||||
apechain "git.frostfs.info/TrueCloudLab/policy-engine/pkg/chain"
|
||||
"github.com/nspcc-dev/neo-go/pkg/util"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
const (
|
||||
namespaceTarget = "namespace"
|
||||
containerTarget = "container"
|
||||
jsonFlag = "json"
|
||||
jsonFlagDesc = "Output rule chains in JSON format"
|
||||
chainIDFlag = "chain-id"
|
||||
chainIDDesc = "Rule chain ID"
|
||||
ruleFlag = "rule"
|
||||
ruleFlagDesc = "Rule chain in text format"
|
||||
ruleJSONFlag = "rule-json"
|
||||
ruleJSONFlagDesc = "Chain rule in JSON format or path to the file"
|
||||
targetNameFlag = "target-name"
|
||||
targetNameDesc = "Resource name in APE resource name format"
|
||||
targetTypeFlag = "target-type"
|
||||
targetTypeDesc = "Resource type(container/namespace)"
|
||||
addrAdminFlag = "addr"
|
||||
addrAdminDesc = "The address of the admins wallet"
|
||||
)
|
||||
|
||||
var (
|
||||
apeCmd = &cobra.Command{
|
||||
Use: "ape",
|
||||
Short: "Section for APE configuration commands",
|
||||
}
|
||||
|
||||
addRuleChainCmd = &cobra.Command{
|
||||
Use: "add-rule-chain",
|
||||
Short: "Add rule chain",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(endpointFlag, cmd.Flags().Lookup(endpointFlag))
|
||||
_ = viper.BindPFlag(alphabetWalletsFlag, cmd.Flags().Lookup(alphabetWalletsFlag))
|
||||
},
|
||||
Run: addRuleChain,
|
||||
}
|
||||
|
||||
removeRuleChainCmd = &cobra.Command{
|
||||
Use: "rm-rule-chain",
|
||||
Short: "Remove rule chain",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(endpointFlag, cmd.Flags().Lookup(endpointFlag))
|
||||
_ = viper.BindPFlag(alphabetWalletsFlag, cmd.Flags().Lookup(alphabetWalletsFlag))
|
||||
},
|
||||
Run: removeRuleChain,
|
||||
}
|
||||
|
||||
listRuleChainsCmd = &cobra.Command{
|
||||
Use: "list-rule-chains",
|
||||
Short: "List rule chains",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(endpointFlag, cmd.Flags().Lookup(endpointFlag))
|
||||
_ = viper.BindPFlag(alphabetWalletsFlag, cmd.Flags().Lookup(alphabetWalletsFlag))
|
||||
},
|
||||
Run: listRuleChains,
|
||||
}
|
||||
|
||||
setAdminCmd = &cobra.Command{
|
||||
Use: "set-admin",
|
||||
Short: "Set admin",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(endpointFlag, cmd.Flags().Lookup(endpointFlag))
|
||||
_ = viper.BindPFlag(alphabetWalletsFlag, cmd.Flags().Lookup(alphabetWalletsFlag))
|
||||
},
|
||||
Run: setAdmin,
|
||||
}
|
||||
|
||||
getAdminCmd = &cobra.Command{
|
||||
Use: "get-admin",
|
||||
Short: "Get admin",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(endpointFlag, cmd.Flags().Lookup(endpointFlag))
|
||||
_ = viper.BindPFlag(alphabetWalletsFlag, cmd.Flags().Lookup(alphabetWalletsFlag))
|
||||
},
|
||||
Run: getAdmin,
|
||||
}
|
||||
)
|
||||
|
||||
func initAddRuleChainCmd() {
|
||||
apeCmd.AddCommand(addRuleChainCmd)
|
||||
|
||||
addRuleChainCmd.Flags().StringP(endpointFlag, endpointFlagShort, "", endpointFlagDesc)
|
||||
addRuleChainCmd.Flags().String(alphabetWalletsFlag, "", alphabetWalletsFlagDesc)
|
||||
|
||||
addRuleChainCmd.Flags().String(targetTypeFlag, "", targetTypeDesc)
|
||||
_ = addRuleChainCmd.MarkFlagRequired(targetTypeFlag)
|
||||
addRuleChainCmd.Flags().String(targetNameFlag, "", targetNameDesc)
|
||||
_ = addRuleChainCmd.MarkFlagRequired(targetNameFlag)
|
||||
|
||||
addRuleChainCmd.Flags().String(chainIDFlag, "", chainIDDesc)
|
||||
_ = addRuleChainCmd.MarkFlagRequired(chainIDFlag)
|
||||
addRuleChainCmd.Flags().String(ruleFlag, "", ruleFlagDesc)
|
||||
addRuleChainCmd.Flags().String(ruleJSONFlag, "", ruleJSONFlagDesc)
|
||||
|
||||
addRuleChainCmd.MarkFlagsMutuallyExclusive(ruleFlag, ruleJSONFlag)
|
||||
}
|
||||
|
||||
func initRemoveRuleChainCmd() {
|
||||
apeCmd.AddCommand(removeRuleChainCmd)
|
||||
|
||||
removeRuleChainCmd.Flags().StringP(endpointFlag, endpointFlagShort, "", endpointFlagDesc)
|
||||
removeRuleChainCmd.Flags().String(alphabetWalletsFlag, "", alphabetWalletsFlagDesc)
|
||||
|
||||
removeRuleChainCmd.Flags().String(targetTypeFlag, "", targetTypeDesc)
|
||||
_ = removeRuleChainCmd.MarkFlagRequired(targetTypeFlag)
|
||||
removeRuleChainCmd.Flags().String(targetNameFlag, "", targetNameDesc)
|
||||
_ = removeRuleChainCmd.MarkFlagRequired(targetNameFlag)
|
||||
removeRuleChainCmd.Flags().String(chainIDFlag, "", chainIDDesc)
|
||||
_ = removeRuleChainCmd.MarkFlagRequired(chainIDFlag)
|
||||
}
|
||||
|
||||
func initListRuleChainsCmd() {
|
||||
apeCmd.AddCommand(listRuleChainsCmd)
|
||||
|
||||
listRuleChainsCmd.Flags().StringP(endpointFlag, endpointFlagShort, "", endpointFlagDesc)
|
||||
listRuleChainsCmd.Flags().String(alphabetWalletsFlag, "", alphabetWalletsFlagDesc)
|
||||
listRuleChainsCmd.Flags().StringP(targetTypeFlag, "t", "", targetTypeDesc)
|
||||
_ = listRuleChainsCmd.MarkFlagRequired(targetTypeFlag)
|
||||
listRuleChainsCmd.Flags().String(targetNameFlag, "", targetNameDesc)
|
||||
_ = listRuleChainsCmd.MarkFlagRequired(targetNameFlag)
|
||||
listRuleChainsCmd.Flags().Bool(jsonFlag, false, jsonFlagDesc)
|
||||
}
|
||||
|
||||
func initSetAdminCmd() {
|
||||
apeCmd.AddCommand(setAdminCmd)
|
||||
|
||||
setAdminCmd.Flags().StringP(endpointFlag, endpointFlagShort, "", endpointFlagDesc)
|
||||
setAdminCmd.Flags().String(alphabetWalletsFlag, "", alphabetWalletsFlagDesc)
|
||||
setAdminCmd.Flags().String(addrAdminFlag, "", addrAdminDesc)
|
||||
_ = setAdminCmd.MarkFlagRequired(addrAdminFlag)
|
||||
}
|
||||
|
||||
func initGetAdminCmd() {
|
||||
apeCmd.AddCommand(getAdminCmd)
|
||||
|
||||
getAdminCmd.Flags().StringP(endpointFlag, endpointFlagShort, "", endpointFlagDesc)
|
||||
getAdminCmd.Flags().String(alphabetWalletsFlag, "", alphabetWalletsFlagDesc)
|
||||
}
|
||||
|
||||
func addRuleChain(cmd *cobra.Command, _ []string) {
|
||||
chain := parseChain(cmd)
|
||||
target := parseTarget(cmd)
|
||||
pci, ac := newPolicyContractInterface(cmd)
|
||||
h, vub, err := pci.AddMorphRuleChain(apechain.Ingress, target, chain)
|
||||
cmd.Println("Waiting for transaction to persist...")
|
||||
_, err = ac.Wait(h, vub, err)
|
||||
commonCmd.ExitOnErr(cmd, "add rule chain error: %w", err)
|
||||
cmd.Println("Rule chain added successfully")
|
||||
}
|
||||
|
||||
func removeRuleChain(cmd *cobra.Command, _ []string) {
|
||||
chainID := parseChainID(cmd)
|
||||
target := parseTarget(cmd)
|
||||
pci, ac := newPolicyContractInterface(cmd)
|
||||
h, vub, err := pci.RemoveMorphRuleChain(apechain.Ingress, target, chainID)
|
||||
cmd.Println("Waiting for transaction to persist...")
|
||||
_, err = ac.Wait(h, vub, err)
|
||||
commonCmd.ExitOnErr(cmd, "remove rule chain error: %w", err)
|
||||
cmd.Println("Rule chain removed successfully")
|
||||
}
|
||||
|
||||
func listRuleChains(cmd *cobra.Command, _ []string) {
|
||||
target := parseTarget(cmd)
|
||||
pci, _ := newPolicyContractInterface(cmd)
|
||||
chains, err := pci.ListMorphRuleChains(apechain.Ingress, target)
|
||||
commonCmd.ExitOnErr(cmd, "list rule chains error: %w", err)
|
||||
if len(chains) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
toJSON, _ := cmd.Flags().GetBool(jsonFlag)
|
||||
if toJSON {
|
||||
prettyJSONFormat(cmd, chains)
|
||||
} else {
|
||||
for _, c := range chains {
|
||||
parseutil.PrintHumanReadableAPEChain(cmd, c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func setAdmin(cmd *cobra.Command, _ []string) {
|
||||
s, _ := cmd.Flags().GetString(addrAdminFlag)
|
||||
addr, err := util.Uint160DecodeStringLE(s)
|
||||
commonCmd.ExitOnErr(cmd, "can't decode admin addr: %w", err)
|
||||
pci, ac := newPolicyContractInterface(cmd)
|
||||
h, vub, err := pci.SetAdmin(addr)
|
||||
cmd.Println("Waiting for transaction to persist...")
|
||||
_, err = ac.Wait(h, vub, err)
|
||||
commonCmd.ExitOnErr(cmd, "can't set admin: %w", err)
|
||||
cmd.Println("Admin set successfully")
|
||||
}
|
||||
|
||||
func getAdmin(cmd *cobra.Command, _ []string) {
|
||||
pci, _ := newPolicyContractInterface(cmd)
|
||||
addr, err := pci.GetAdmin()
|
||||
commonCmd.ExitOnErr(cmd, "unable to get admin: %w", err)
|
||||
cmd.Println(addr.StringLE())
|
||||
}
|
||||
|
||||
func prettyJSONFormat(cmd *cobra.Command, chains []*apechain.Chain) {
|
||||
wr := bytes.NewBufferString("")
|
||||
data, err := json.Marshal(chains)
|
||||
if err == nil {
|
||||
err = json.Indent(wr, data, "", " ")
|
||||
}
|
||||
commonCmd.ExitOnErr(cmd, "print rule chain error: %w", err)
|
||||
cmd.Println(wr)
|
||||
}
|
250
cmd/frostfs-adm/internal/modules/morph/ape/ape.go
Normal file
250
cmd/frostfs-adm/internal/modules/morph/ape/ape.go
Normal file
|
@ -0,0 +1,250 @@
|
|||
package ape
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
commonCmd "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/internal/common"
|
||||
apeCmd "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/internal/common/ape"
|
||||
apechain "git.frostfs.info/TrueCloudLab/policy-engine/pkg/chain"
|
||||
"github.com/nspcc-dev/neo-go/pkg/encoding/address"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
const (
|
||||
jsonFlag = "json"
|
||||
jsonFlagDesc = "Output rule chains in JSON format"
|
||||
addrAdminFlag = "addr"
|
||||
addrAdminDesc = "The address of the admins wallet"
|
||||
)
|
||||
|
||||
var (
|
||||
addRuleChainCmd = &cobra.Command{
|
||||
Use: "add-rule-chain",
|
||||
Short: "Add rule chain",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
_ = viper.BindPFlag(commonflags.AlphabetWalletsFlag, cmd.Flags().Lookup(commonflags.AlphabetWalletsFlag))
|
||||
},
|
||||
Run: addRuleChain,
|
||||
}
|
||||
|
||||
removeRuleChainCmd = &cobra.Command{
|
||||
Use: "rm-rule-chain",
|
||||
Short: "Remove rule chain",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
_ = viper.BindPFlag(commonflags.AlphabetWalletsFlag, cmd.Flags().Lookup(commonflags.AlphabetWalletsFlag))
|
||||
},
|
||||
Run: removeRuleChain,
|
||||
}
|
||||
|
||||
listRuleChainsCmd = &cobra.Command{
|
||||
Use: "list-rule-chains",
|
||||
Short: "List rule chains",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
Run: listRuleChains,
|
||||
}
|
||||
|
||||
setAdminCmd = &cobra.Command{
|
||||
Use: "set-admin",
|
||||
Short: "Set admin",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
_ = viper.BindPFlag(commonflags.AlphabetWalletsFlag, cmd.Flags().Lookup(commonflags.AlphabetWalletsFlag))
|
||||
},
|
||||
Run: setAdmin,
|
||||
}
|
||||
|
||||
getAdminCmd = &cobra.Command{
|
||||
Use: "get-admin",
|
||||
Short: "Get admin",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
Run: getAdmin,
|
||||
}
|
||||
|
||||
listTargetsCmd = &cobra.Command{
|
||||
Use: "list-targets",
|
||||
Short: "List targets",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
Run: listTargets,
|
||||
}
|
||||
)
|
||||
|
||||
func initAddRuleChainCmd() {
|
||||
Cmd.AddCommand(addRuleChainCmd)
|
||||
|
||||
addRuleChainCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
addRuleChainCmd.Flags().String(commonflags.AlphabetWalletsFlag, "", commonflags.AlphabetWalletsFlagDesc)
|
||||
|
||||
addRuleChainCmd.Flags().String(apeCmd.TargetTypeFlag, "", apeCmd.TargetTypeFlagDesc)
|
||||
_ = addRuleChainCmd.MarkFlagRequired(apeCmd.TargetTypeFlag)
|
||||
addRuleChainCmd.Flags().String(apeCmd.TargetNameFlag, "", apeCmd.TargetTypeFlagDesc)
|
||||
_ = addRuleChainCmd.MarkFlagRequired(apeCmd.TargetNameFlag)
|
||||
|
||||
addRuleChainCmd.Flags().String(apeCmd.ChainIDFlag, "", apeCmd.ChainIDFlagDesc)
|
||||
_ = addRuleChainCmd.MarkFlagRequired(apeCmd.ChainIDFlag)
|
||||
addRuleChainCmd.Flags().StringArray(apeCmd.RuleFlag, []string{}, apeCmd.RuleFlagDesc)
|
||||
addRuleChainCmd.Flags().String(apeCmd.PathFlag, "", apeCmd.PathFlagDesc)
|
||||
addRuleChainCmd.Flags().String(apeCmd.ChainNameFlag, apeCmd.Ingress, apeCmd.ChainNameFlagDesc)
|
||||
addRuleChainCmd.MarkFlagsMutuallyExclusive(apeCmd.RuleFlag, apeCmd.PathFlag)
|
||||
}
|
||||
|
||||
func initRemoveRuleChainCmd() {
|
||||
Cmd.AddCommand(removeRuleChainCmd)
|
||||
|
||||
removeRuleChainCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
removeRuleChainCmd.Flags().String(commonflags.AlphabetWalletsFlag, "", commonflags.AlphabetWalletsFlagDesc)
|
||||
|
||||
removeRuleChainCmd.Flags().String(apeCmd.TargetTypeFlag, "", apeCmd.TargetTypeFlagDesc)
|
||||
_ = removeRuleChainCmd.MarkFlagRequired(apeCmd.TargetTypeFlag)
|
||||
removeRuleChainCmd.Flags().String(apeCmd.TargetNameFlag, "", apeCmd.TargetNameFlagDesc)
|
||||
_ = removeRuleChainCmd.MarkFlagRequired(apeCmd.TargetNameFlag)
|
||||
removeRuleChainCmd.Flags().String(apeCmd.ChainIDFlag, "", apeCmd.ChainIDFlagDesc)
|
||||
removeRuleChainCmd.Flags().String(apeCmd.ChainNameFlag, apeCmd.Ingress, apeCmd.ChainNameFlagDesc)
|
||||
removeRuleChainCmd.Flags().Bool(commonflags.AllFlag, false, "Remove all chains for target")
|
||||
removeRuleChainCmd.MarkFlagsMutuallyExclusive(commonflags.AllFlag, apeCmd.ChainIDFlag)
|
||||
}
|
||||
|
||||
func initListRuleChainsCmd() {
|
||||
Cmd.AddCommand(listRuleChainsCmd)
|
||||
|
||||
listRuleChainsCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
listRuleChainsCmd.Flags().StringP(apeCmd.TargetTypeFlag, "t", "", apeCmd.TargetTypeFlagDesc)
|
||||
_ = listRuleChainsCmd.MarkFlagRequired(apeCmd.TargetTypeFlag)
|
||||
listRuleChainsCmd.Flags().String(apeCmd.TargetNameFlag, "", apeCmd.TargetNameFlagDesc)
|
||||
listRuleChainsCmd.Flags().Bool(jsonFlag, false, jsonFlagDesc)
|
||||
listRuleChainsCmd.Flags().String(apeCmd.ChainNameFlag, apeCmd.Ingress, apeCmd.ChainNameFlagDesc)
|
||||
}
|
||||
|
||||
func initSetAdminCmd() {
|
||||
Cmd.AddCommand(setAdminCmd)
|
||||
|
||||
setAdminCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
setAdminCmd.Flags().String(commonflags.AlphabetWalletsFlag, "", commonflags.AlphabetWalletsFlagDesc)
|
||||
setAdminCmd.Flags().String(addrAdminFlag, "", addrAdminDesc)
|
||||
_ = setAdminCmd.MarkFlagRequired(addrAdminFlag)
|
||||
}
|
||||
|
||||
func initGetAdminCmd() {
|
||||
Cmd.AddCommand(getAdminCmd)
|
||||
|
||||
getAdminCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
}
|
||||
|
||||
func initListTargetsCmd() {
|
||||
Cmd.AddCommand(listTargetsCmd)
|
||||
|
||||
listTargetsCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
listTargetsCmd.Flags().StringP(apeCmd.TargetTypeFlag, "t", "", apeCmd.TargetTypeFlagDesc)
|
||||
_ = listTargetsCmd.MarkFlagRequired(apeCmd.TargetTypeFlag)
|
||||
}
|
||||
|
||||
func addRuleChain(cmd *cobra.Command, _ []string) {
|
||||
chain := apeCmd.ParseChain(cmd)
|
||||
target := parseTarget(cmd)
|
||||
pci, ac := newPolicyContractInterface(cmd)
|
||||
h, vub, err := pci.AddMorphRuleChain(apeCmd.ParseChainName(cmd), target, chain)
|
||||
cmd.Println("Waiting for transaction to persist...")
|
||||
_, err = ac.Wait(h, vub, err)
|
||||
commonCmd.ExitOnErr(cmd, "add rule chain error: %w", err)
|
||||
cmd.Println("Rule chain added successfully")
|
||||
}
|
||||
|
||||
func removeRuleChain(cmd *cobra.Command, _ []string) {
|
||||
target := parseTarget(cmd)
|
||||
pci, ac := newPolicyContractInterface(cmd)
|
||||
removeAll, _ := cmd.Flags().GetBool(commonflags.AllFlag)
|
||||
if removeAll {
|
||||
h, vub, err := pci.RemoveMorphRuleChainsByTarget(apeCmd.ParseChainName(cmd), target)
|
||||
cmd.Println("Waiting for transaction to persist...")
|
||||
_, err = ac.Wait(h, vub, err)
|
||||
commonCmd.ExitOnErr(cmd, "remove rule chain error: %w", err)
|
||||
cmd.Println("All chains for target removed successfully")
|
||||
} else {
|
||||
chainID := apeCmd.ParseChainID(cmd)
|
||||
h, vub, err := pci.RemoveMorphRuleChain(apeCmd.ParseChainName(cmd), target, chainID)
|
||||
cmd.Println("Waiting for transaction to persist...")
|
||||
_, err = ac.Wait(h, vub, err)
|
||||
commonCmd.ExitOnErr(cmd, "remove rule chain error: %w", err)
|
||||
cmd.Println("Rule chain removed successfully")
|
||||
}
|
||||
}
|
||||
|
||||
func listRuleChains(cmd *cobra.Command, _ []string) {
|
||||
target := parseTarget(cmd)
|
||||
pci, _ := newPolicyContractReaderInterface(cmd)
|
||||
chains, err := pci.ListMorphRuleChains(apeCmd.ParseChainName(cmd), target)
|
||||
commonCmd.ExitOnErr(cmd, "list rule chains error: %w", err)
|
||||
if len(chains) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
toJSON, _ := cmd.Flags().GetBool(jsonFlag)
|
||||
if toJSON {
|
||||
prettyJSONFormat(cmd, chains)
|
||||
} else {
|
||||
for _, c := range chains {
|
||||
apeCmd.PrintHumanReadableAPEChain(cmd, c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func setAdmin(cmd *cobra.Command, _ []string) {
|
||||
s, _ := cmd.Flags().GetString(addrAdminFlag)
|
||||
addr, err := address.StringToUint160(s)
|
||||
commonCmd.ExitOnErr(cmd, "can't decode admin addr: %w", err)
|
||||
pci, ac := newPolicyContractInterface(cmd)
|
||||
h, vub, err := pci.SetAdmin(addr)
|
||||
cmd.Println("Waiting for transaction to persist...")
|
||||
_, err = ac.Wait(h, vub, err)
|
||||
commonCmd.ExitOnErr(cmd, "can't set admin: %w", err)
|
||||
cmd.Println("Admin set successfully")
|
||||
}
|
||||
|
||||
func getAdmin(cmd *cobra.Command, _ []string) {
|
||||
pci, _ := newPolicyContractReaderInterface(cmd)
|
||||
addr, err := pci.GetAdmin()
|
||||
commonCmd.ExitOnErr(cmd, "unable to get admin: %w", err)
|
||||
cmd.Println(address.Uint160ToString(addr))
|
||||
}
|
||||
|
||||
func listTargets(cmd *cobra.Command, _ []string) {
|
||||
typ := apeCmd.ParseTargetType(cmd)
|
||||
pci, inv := newPolicyContractReaderInterface(cmd)
|
||||
|
||||
sid, it, err := pci.ListTargetsIterator(typ)
|
||||
commonCmd.ExitOnErr(cmd, "list targets error: %w", err)
|
||||
items, err := inv.TraverseIterator(sid, &it, 0)
|
||||
for err == nil && len(items) != 0 {
|
||||
for _, item := range items {
|
||||
bts, err := item.TryBytes()
|
||||
commonCmd.ExitOnErr(cmd, "list targets error: %w", err)
|
||||
if len(bts) == 0 {
|
||||
cmd.Println("(no name)")
|
||||
} else {
|
||||
cmd.Println(string(bts))
|
||||
}
|
||||
}
|
||||
items, err = inv.TraverseIterator(sid, &it, 0)
|
||||
commonCmd.ExitOnErr(cmd, "unable to list targets: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
func prettyJSONFormat(cmd *cobra.Command, chains []*apechain.Chain) {
|
||||
wr := bytes.NewBufferString("")
|
||||
data, err := json.Marshal(chains)
|
||||
if err == nil {
|
||||
err = json.Indent(wr, data, "", " ")
|
||||
}
|
||||
commonCmd.ExitOnErr(cmd, "print rule chain error: %w", err)
|
||||
cmd.Println(wr)
|
||||
}
|
91
cmd/frostfs-adm/internal/modules/morph/ape/ape_util.go
Normal file
91
cmd/frostfs-adm/internal/modules/morph/ape/ape_util.go
Normal file
|
@ -0,0 +1,91 @@
|
|||
package ape
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/constants"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/helper"
|
||||
commonCmd "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/internal/common"
|
||||
apeCmd "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/internal/common/ape"
|
||||
cid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container/id"
|
||||
policyengine "git.frostfs.info/TrueCloudLab/policy-engine/pkg/engine"
|
||||
morph "git.frostfs.info/TrueCloudLab/policy-engine/pkg/morph/policy"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/invoker"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/management"
|
||||
"github.com/nspcc-dev/neo-go/pkg/util"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var errUnknownTargetType = errors.New("unknown target type")
|
||||
|
||||
func parseTarget(cmd *cobra.Command) policyengine.Target {
|
||||
typ := apeCmd.ParseTargetType(cmd)
|
||||
name, _ := cmd.Flags().GetString(apeCmd.TargetNameFlag)
|
||||
switch typ {
|
||||
case policyengine.Namespace:
|
||||
if name == "root" {
|
||||
name = ""
|
||||
}
|
||||
return policyengine.NamespaceTarget(name)
|
||||
case policyengine.Container:
|
||||
var cnr cid.ID
|
||||
commonCmd.ExitOnErr(cmd, "can't decode container ID: %w", cnr.DecodeString(name))
|
||||
return policyengine.ContainerTarget(name)
|
||||
case policyengine.User:
|
||||
return policyengine.UserTarget(name)
|
||||
case policyengine.Group:
|
||||
return policyengine.GroupTarget(name)
|
||||
default:
|
||||
commonCmd.ExitOnErr(cmd, "read target type error: %w", errUnknownTargetType)
|
||||
}
|
||||
panic("unreachable")
|
||||
}
|
||||
|
||||
// invokerAdapter adapats invoker.Invoker to ContractStorageInvoker interface.
|
||||
type invokerAdapter struct {
|
||||
*invoker.Invoker
|
||||
rpcActor invoker.RPCInvoke
|
||||
}
|
||||
|
||||
func (n *invokerAdapter) GetRPCInvoker() invoker.RPCInvoke {
|
||||
return n.rpcActor
|
||||
}
|
||||
|
||||
func newPolicyContractReaderInterface(cmd *cobra.Command) (*morph.ContractStorageReader, *invoker.Invoker) {
|
||||
c, err := helper.NewRemoteClient(viper.GetViper())
|
||||
commonCmd.ExitOnErr(cmd, "unable to create NEO rpc client: %w", err)
|
||||
|
||||
inv := invoker.New(c, nil)
|
||||
r := management.NewReader(inv)
|
||||
nnsCs, err := helper.GetContractByID(r, 1)
|
||||
commonCmd.ExitOnErr(cmd, "can't get NNS contract state: %w", err)
|
||||
|
||||
ch, err := helper.NNSResolveHash(inv, nnsCs.Hash, helper.DomainOf(constants.PolicyContract))
|
||||
commonCmd.ExitOnErr(cmd, "unable to resolve policy contract hash: %w", err)
|
||||
|
||||
invokerAdapter := &invokerAdapter{
|
||||
Invoker: inv,
|
||||
rpcActor: c,
|
||||
}
|
||||
|
||||
return morph.NewContractStorageReader(invokerAdapter, ch), inv
|
||||
}
|
||||
|
||||
func newPolicyContractInterface(cmd *cobra.Command) (*morph.ContractStorage, *helper.LocalActor) {
|
||||
c, err := helper.NewRemoteClient(viper.GetViper())
|
||||
commonCmd.ExitOnErr(cmd, "unable to create NEO rpc client: %w", err)
|
||||
|
||||
ac, err := helper.NewLocalActor(cmd, c, constants.ConsensusAccountName)
|
||||
commonCmd.ExitOnErr(cmd, "can't create actor: %w", err)
|
||||
|
||||
var ch util.Uint160
|
||||
r := management.NewReader(ac.Invoker)
|
||||
nnsCs, err := helper.GetContractByID(r, 1)
|
||||
commonCmd.ExitOnErr(cmd, "can't get NNS contract state: %w", err)
|
||||
|
||||
ch, err = helper.NNSResolveHash(ac.Invoker, nnsCs.Hash, helper.DomainOf(constants.PolicyContract))
|
||||
commonCmd.ExitOnErr(cmd, "unable to resolve policy contract hash: %w", err)
|
||||
|
||||
return morph.NewContractStorage(ac, ch), ac
|
||||
}
|
17
cmd/frostfs-adm/internal/modules/morph/ape/root.go
Normal file
17
cmd/frostfs-adm/internal/modules/morph/ape/root.go
Normal file
|
@ -0,0 +1,17 @@
|
|||
package ape
|
||||
|
||||
import "github.com/spf13/cobra"
|
||||
|
||||
var Cmd = &cobra.Command{
|
||||
Use: "ape",
|
||||
Short: "Section for APE configuration commands",
|
||||
}
|
||||
|
||||
func init() {
|
||||
initAddRuleChainCmd()
|
||||
initRemoveRuleChainCmd()
|
||||
initListRuleChainsCmd()
|
||||
initSetAdminCmd()
|
||||
initGetAdminCmd()
|
||||
initListTargetsCmd()
|
||||
}
|
|
@ -1,103 +0,0 @@
|
|||
package morph
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/config"
|
||||
parseutil "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-cli/modules/util"
|
||||
commonCmd "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/internal/common"
|
||||
apechain "git.frostfs.info/TrueCloudLab/policy-engine/pkg/chain"
|
||||
policyengine "git.frostfs.info/TrueCloudLab/policy-engine/pkg/engine"
|
||||
morph "git.frostfs.info/TrueCloudLab/policy-engine/pkg/morph/policy"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/actor"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/management"
|
||||
"github.com/nspcc-dev/neo-go/pkg/util"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
func parseTarget(cmd *cobra.Command) policyengine.Target {
|
||||
var targetType policyengine.TargetType
|
||||
typ, _ := cmd.Flags().GetString(targetTypeFlag)
|
||||
switch typ {
|
||||
case namespaceTarget:
|
||||
targetType = policyengine.Namespace
|
||||
case containerTarget:
|
||||
targetType = policyengine.Container
|
||||
default:
|
||||
commonCmd.ExitOnErr(cmd, "read target type error: %w", fmt.Errorf("unknown target type"))
|
||||
}
|
||||
name, _ := cmd.Flags().GetString(targetNameFlag)
|
||||
|
||||
return policyengine.Target{
|
||||
Name: name,
|
||||
Type: targetType,
|
||||
}
|
||||
}
|
||||
|
||||
func parseChainID(cmd *cobra.Command) apechain.ID {
|
||||
chainID, _ := cmd.Flags().GetString(chainIDFlag)
|
||||
if chainID == "" {
|
||||
commonCmd.ExitOnErr(cmd, "read chain id error: %w",
|
||||
fmt.Errorf("chain id cannot be empty"))
|
||||
}
|
||||
return apechain.ID(chainID)
|
||||
}
|
||||
|
||||
func parseChain(cmd *cobra.Command) *apechain.Chain {
|
||||
chain := new(apechain.Chain)
|
||||
|
||||
if ruleStmt, _ := cmd.Flags().GetString(ruleFlag); ruleStmt != "" {
|
||||
parseErr := parseutil.ParseAPEChain(chain, []string{ruleStmt})
|
||||
commonCmd.ExitOnErr(cmd, "ape chain parser error: %w", parseErr)
|
||||
} else if ruleJSON, _ := cmd.Flags().GetString(ruleJSONFlag); ruleJSON != "" {
|
||||
var rule []byte
|
||||
if _, err := os.Stat(ruleJSON); err == nil {
|
||||
rule, err = os.ReadFile(ruleJSON)
|
||||
commonCmd.ExitOnErr(cmd, "read file error: %w", err)
|
||||
} else {
|
||||
rule = []byte(ruleJSON)
|
||||
if !json.Valid(rule) {
|
||||
commonCmd.ExitOnErr(cmd, "read raw rule error: %w",
|
||||
fmt.Errorf("invalid JSON"))
|
||||
}
|
||||
}
|
||||
err := chain.DecodeBytes(rule)
|
||||
commonCmd.ExitOnErr(cmd, "chain decode error: %w", err)
|
||||
} else {
|
||||
commonCmd.ExitOnErr(cmd, "", fmt.Errorf("rule is not passed"))
|
||||
}
|
||||
|
||||
chain.ID = parseChainID(cmd)
|
||||
|
||||
return chain
|
||||
}
|
||||
|
||||
func newPolicyContractInterface(cmd *cobra.Command) (*morph.ContractStorage, *actor.Actor) {
|
||||
v := viper.GetViper()
|
||||
c, err := getN3Client(v)
|
||||
commonCmd.ExitOnErr(cmd, "unable to create NEO rpc client: %w", err)
|
||||
|
||||
walletDir := config.ResolveHomePath(viper.GetString(alphabetWalletsFlag))
|
||||
wallets, err := getAlphabetWallets(v, walletDir)
|
||||
commonCmd.ExitOnErr(cmd, "unable to get alphabet wallets: %w", err)
|
||||
|
||||
committeeAcc, err := getWalletAccount(wallets[0], committeeAccountName)
|
||||
commonCmd.ExitOnErr(cmd, "can't find committee account: %w", err)
|
||||
|
||||
ac, err := newActor(c, committeeAcc)
|
||||
commonCmd.ExitOnErr(cmd, "can't create actor: %w", err)
|
||||
|
||||
inv := &ac.Invoker
|
||||
var ch util.Uint160
|
||||
r := management.NewReader(inv)
|
||||
nnsCs, err := r.GetContractByID(1)
|
||||
commonCmd.ExitOnErr(cmd, "can't get NNS contract state: %w", err)
|
||||
|
||||
ch, err = nnsResolveHash(inv, nnsCs.Hash, domainOf(policyContract))
|
||||
commonCmd.ExitOnErr(cmd, "unable to resolve policy contract hash: %w", err)
|
||||
|
||||
return morph.NewContractStorage(ac, ch), ac
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package morph
|
||||
package balance
|
||||
|
||||
import (
|
||||
"crypto/elliptic"
|
||||
|
@ -7,6 +7,8 @@ import (
|
|||
"math/big"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-contract/nns"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/constants"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/helper"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-sdk-go/netmap"
|
||||
"github.com/nspcc-dev/neo-go/pkg/core/native/noderoles"
|
||||
"github.com/nspcc-dev/neo-go/pkg/core/state"
|
||||
|
@ -49,7 +51,7 @@ func dumpBalances(cmd *cobra.Command, _ []string) error {
|
|||
nmHash util.Uint160
|
||||
)
|
||||
|
||||
c, err := getN3Client(viper.GetViper())
|
||||
c, err := helper.NewRemoteClient(viper.GetViper())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
@ -58,12 +60,12 @@ func dumpBalances(cmd *cobra.Command, _ []string) error {
|
|||
|
||||
if dumpStorage || dumpAlphabet || dumpProxy {
|
||||
r := management.NewReader(inv)
|
||||
nnsCs, err = r.GetContractByID(1)
|
||||
nnsCs, err = helper.GetContractByID(r, 1)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't get NNS contract info: %w", err)
|
||||
}
|
||||
|
||||
nmHash, err = nnsResolveHash(inv, nnsCs.Hash, domainOf(netmapContract))
|
||||
nmHash, err = helper.NNSResolveHash(inv, nnsCs.Hash, helper.DomainOf(constants.NetmapContract))
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't get netmap contract hash: %w", err)
|
||||
}
|
||||
|
@ -136,7 +138,7 @@ func printStorageNodeBalances(cmd *cobra.Command, inv *invoker.Invoker, nmHash u
|
|||
}
|
||||
|
||||
func printProxyContractBalance(cmd *cobra.Command, inv *invoker.Invoker, nnsHash util.Uint160) error {
|
||||
h, err := nnsResolveHash(inv, nnsHash, domainOf(proxyContract))
|
||||
h, err := helper.NNSResolveHash(inv, nnsHash, helper.DomainOf(constants.ProxyContract))
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't get hash of the proxy contract: %w", err)
|
||||
}
|
||||
|
@ -150,13 +152,13 @@ func printProxyContractBalance(cmd *cobra.Command, inv *invoker.Invoker, nnsHash
|
|||
return nil
|
||||
}
|
||||
|
||||
func printAlphabetContractBalances(cmd *cobra.Command, c Client, inv *invoker.Invoker, count int, nnsHash util.Uint160) error {
|
||||
func printAlphabetContractBalances(cmd *cobra.Command, c helper.Client, inv *invoker.Invoker, count int, nnsHash util.Uint160) error {
|
||||
alphaList := make([]accBalancePair, count)
|
||||
|
||||
w := io.NewBufBinWriter()
|
||||
for i := range alphaList {
|
||||
emit.AppCall(w.BinWriter, nnsHash, "resolve", callflag.ReadOnly,
|
||||
getAlphabetNNSDomain(i),
|
||||
helper.GetAlphabetNNSDomain(i),
|
||||
int64(nns.TXT))
|
||||
}
|
||||
if w.Err != nil {
|
||||
|
@ -169,7 +171,7 @@ func printAlphabetContractBalances(cmd *cobra.Command, c Client, inv *invoker.In
|
|||
}
|
||||
|
||||
for i := range alphaList {
|
||||
h, err := parseNNSResolveResult(alphaRes.Stack[i])
|
||||
h, err := helper.ParseNNSResolveResult(alphaRes.Stack[i])
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't fetch the alphabet contract #%d hash: %w", i, err)
|
||||
}
|
||||
|
@ -184,7 +186,7 @@ func printAlphabetContractBalances(cmd *cobra.Command, c Client, inv *invoker.In
|
|||
return nil
|
||||
}
|
||||
|
||||
func fetchIRNodes(c Client, desigHash util.Uint160) ([]accBalancePair, error) {
|
||||
func fetchIRNodes(c helper.Client, desigHash util.Uint160) ([]accBalancePair, error) {
|
||||
inv := invoker.New(c, nil)
|
||||
|
||||
height, err := c.GetBlockCount()
|
||||
|
@ -192,7 +194,7 @@ func fetchIRNodes(c Client, desigHash util.Uint160) ([]accBalancePair, error) {
|
|||
return nil, fmt.Errorf("can't get block height: %w", err)
|
||||
}
|
||||
|
||||
arr, err := getDesignatedByRole(inv, desigHash, noderoles.NeoFSAlphabet, height)
|
||||
arr, err := helper.GetDesignatedByRole(inv, desigHash, noderoles.NeoFSAlphabet, height)
|
||||
if err != nil {
|
||||
return nil, errors.New("can't fetch list of IR nodes from the netmap contract")
|
||||
}
|
28
cmd/frostfs-adm/internal/modules/morph/balance/root.go
Normal file
28
cmd/frostfs-adm/internal/modules/morph/balance/root.go
Normal file
|
@ -0,0 +1,28 @@
|
|||
package balance
|
||||
|
||||
import (
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var DumpCmd = &cobra.Command{
|
||||
Use: "dump-balances",
|
||||
Short: "Dump GAS balances",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
RunE: dumpBalances,
|
||||
}
|
||||
|
||||
func initDumpBalancesCmd() {
|
||||
DumpCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
DumpCmd.Flags().BoolP(dumpBalancesStorageFlag, "s", false, "Dump balances of storage nodes from the current netmap")
|
||||
DumpCmd.Flags().BoolP(dumpBalancesAlphabetFlag, "a", false, "Dump balances of alphabet contracts")
|
||||
DumpCmd.Flags().BoolP(dumpBalancesProxyFlag, "p", false, "Dump balances of the proxy contract")
|
||||
DumpCmd.Flags().Bool(dumpBalancesUseScriptHashFlag, false, "Use script-hash format for addresses")
|
||||
}
|
||||
|
||||
func init() {
|
||||
initDumpBalancesCmd()
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package morph
|
||||
package config
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
|
@ -10,6 +10,8 @@ import (
|
|||
"strings"
|
||||
"text/tabwriter"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/constants"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/helper"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/morph/client/netmap"
|
||||
"github.com/nspcc-dev/neo-go/pkg/io"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/invoker"
|
||||
|
@ -24,7 +26,7 @@ import (
|
|||
const forceConfigSet = "force"
|
||||
|
||||
func dumpNetworkConfig(cmd *cobra.Command, _ []string) error {
|
||||
c, err := getN3Client(viper.GetViper())
|
||||
c, err := helper.NewRemoteClient(viper.GetViper())
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't create N3 client: %w", err)
|
||||
}
|
||||
|
@ -32,12 +34,12 @@ func dumpNetworkConfig(cmd *cobra.Command, _ []string) error {
|
|||
inv := invoker.New(c, nil)
|
||||
r := management.NewReader(inv)
|
||||
|
||||
cs, err := r.GetContractByID(1)
|
||||
cs, err := helper.GetContractByID(r, 1)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't get NNS contract info: %w", err)
|
||||
}
|
||||
|
||||
nmHash, err := nnsResolveHash(inv, cs.Hash, domainOf(netmapContract))
|
||||
nmHash, err := helper.NNSResolveHash(inv, cs.Hash, helper.DomainOf(constants.NetmapContract))
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't get netmap contract hash: %w", err)
|
||||
}
|
||||
|
@ -50,7 +52,7 @@ func dumpNetworkConfig(cmd *cobra.Command, _ []string) error {
|
|||
buf := bytes.NewBuffer(nil)
|
||||
tw := tabwriter.NewWriter(buf, 0, 2, 2, ' ', 0)
|
||||
|
||||
m, err := parseConfigFromNetmapContract(arr)
|
||||
m, err := helper.ParseConfigFromNetmapContract(arr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
@ -58,14 +60,15 @@ func dumpNetworkConfig(cmd *cobra.Command, _ []string) error {
|
|||
switch k {
|
||||
case netmap.ContainerFeeConfig, netmap.ContainerAliasFeeConfig,
|
||||
netmap.EpochDurationConfig, netmap.IrCandidateFeeConfig,
|
||||
netmap.MaxObjectSizeConfig, netmap.WithdrawFeeConfig:
|
||||
netmap.MaxObjectSizeConfig, netmap.WithdrawFeeConfig,
|
||||
netmap.MaxECDataCountConfig, netmap.MaxECParityCountConfig:
|
||||
nbuf := make([]byte, 8)
|
||||
copy(nbuf[:], v)
|
||||
n := binary.LittleEndian.Uint64(nbuf)
|
||||
_, _ = tw.Write([]byte(fmt.Sprintf("%s:\t%d (int)\n", k, n)))
|
||||
case netmap.HomomorphicHashingDisabledKey, netmap.MaintenanceModeAllowedConfig:
|
||||
if len(v) == 0 || len(v) > 1 {
|
||||
return invalidConfigValueErr(k)
|
||||
return helper.InvalidConfigValueErr(k)
|
||||
}
|
||||
_, _ = tw.Write([]byte(fmt.Sprintf("%s:\t%t (bool)\n", k, v[0] == 1)))
|
||||
default:
|
||||
|
@ -79,36 +82,44 @@ func dumpNetworkConfig(cmd *cobra.Command, _ []string) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func setConfigCmd(cmd *cobra.Command, args []string) error {
|
||||
func SetConfigCmd(cmd *cobra.Command, args []string) error {
|
||||
if len(args) == 0 {
|
||||
return errors.New("empty config pairs")
|
||||
}
|
||||
|
||||
wCtx, err := newInitializeContext(cmd, viper.GetViper())
|
||||
wCtx, err := helper.NewInitializeContext(cmd, viper.GetViper())
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't initialize context: %w", err)
|
||||
}
|
||||
|
||||
r := management.NewReader(wCtx.ReadOnlyInvoker)
|
||||
cs, err := r.GetContractByID(1)
|
||||
cs, err := helper.GetContractByID(r, 1)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't get NNS contract info: %w", err)
|
||||
}
|
||||
|
||||
nmHash, err := nnsResolveHash(wCtx.ReadOnlyInvoker, cs.Hash, domainOf(netmapContract))
|
||||
nmHash, err := helper.NNSResolveHash(wCtx.ReadOnlyInvoker, cs.Hash, helper.DomainOf(constants.NetmapContract))
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't get netmap contract hash: %w", err)
|
||||
}
|
||||
|
||||
forceFlag, _ := cmd.Flags().GetBool(forceConfigSet)
|
||||
|
||||
bw := io.NewBufBinWriter()
|
||||
prm := make(map[string]any)
|
||||
for _, arg := range args {
|
||||
k, v, err := parseConfigPair(arg, forceFlag)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
prm[k] = v
|
||||
}
|
||||
|
||||
if err := validateConfig(prm, forceFlag); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for k, v := range prm {
|
||||
// In NeoFS this is done via Notary contract. Here, however, we can form the
|
||||
// transaction locally. The first `nil` argument is required only for notary
|
||||
// disabled environment which is not supported by that command.
|
||||
|
@ -118,12 +129,56 @@ func setConfigCmd(cmd *cobra.Command, args []string) error {
|
|||
}
|
||||
}
|
||||
|
||||
err = wCtx.sendConsensusTx(bw.Bytes())
|
||||
err = wCtx.SendConsensusTx(bw.Bytes())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return wCtx.awaitTx()
|
||||
return wCtx.AwaitTx()
|
||||
}
|
||||
|
||||
const maxECSum = 256
|
||||
|
||||
func validateConfig(args map[string]any, forceFlag bool) error {
|
||||
var sumEC int64
|
||||
_, okData := args[netmap.MaxECDataCountConfig]
|
||||
_, okParity := args[netmap.MaxECParityCountConfig]
|
||||
if okData != okParity {
|
||||
return fmt.Errorf("both %s and %s must be present in the configuration",
|
||||
netmap.MaxECDataCountConfig, netmap.MaxECParityCountConfig)
|
||||
}
|
||||
|
||||
for k, v := range args {
|
||||
switch k {
|
||||
case netmap.ContainerFeeConfig, netmap.ContainerAliasFeeConfig,
|
||||
netmap.EpochDurationConfig, netmap.IrCandidateFeeConfig,
|
||||
netmap.MaxObjectSizeConfig, netmap.WithdrawFeeConfig,
|
||||
netmap.MaxECDataCountConfig, netmap.MaxECParityCountConfig:
|
||||
value, ok := v.(int64)
|
||||
if !ok {
|
||||
return fmt.Errorf("%s has an invalid type. Expected type: int", k)
|
||||
}
|
||||
|
||||
if value < 0 {
|
||||
return fmt.Errorf("%s must be >= 0, got %v", k, v)
|
||||
}
|
||||
|
||||
if k == netmap.MaxECDataCountConfig || k == netmap.MaxECParityCountConfig {
|
||||
sumEC += value
|
||||
}
|
||||
case netmap.HomomorphicHashingDisabledKey, netmap.MaintenanceModeAllowedConfig:
|
||||
_, ok := v.(bool)
|
||||
if !ok {
|
||||
return fmt.Errorf("%s has an invalid type. Expected type: bool", k)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if sumEC > maxECSum && !forceFlag {
|
||||
return fmt.Errorf("the sum of %s and %s must be <= %d, got %d",
|
||||
netmap.MaxECDataCountConfig, netmap.MaxECParityCountConfig, maxECSum, sumEC)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseConfigPair(kvStr string, force bool) (key string, val any, err error) {
|
||||
|
@ -138,7 +193,8 @@ func parseConfigPair(kvStr string, force bool) (key string, val any, err error)
|
|||
switch key {
|
||||
case netmap.ContainerFeeConfig, netmap.ContainerAliasFeeConfig,
|
||||
netmap.EpochDurationConfig, netmap.IrCandidateFeeConfig,
|
||||
netmap.MaxObjectSizeConfig, netmap.WithdrawFeeConfig:
|
||||
netmap.MaxObjectSizeConfig, netmap.WithdrawFeeConfig,
|
||||
netmap.MaxECDataCountConfig, netmap.MaxECParityCountConfig:
|
||||
val, err = strconv.ParseInt(valRaw, 10, 64)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("could not parse %s's value '%s' as int: %w", key, valRaw, err)
|
||||
|
@ -161,7 +217,3 @@ func parseConfigPair(kvStr string, force bool) (key string, val any, err error)
|
|||
|
||||
return
|
||||
}
|
||||
|
||||
func invalidConfigValueErr(key string) error {
|
||||
return fmt.Errorf("invalid %s config value from netmap contract", key)
|
||||
}
|
34
cmd/frostfs-adm/internal/modules/morph/config/config_test.go
Normal file
34
cmd/frostfs-adm/internal/modules/morph/config/config_test.go
Normal file
|
@ -0,0 +1,34 @@
|
|||
package config
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/morph/client/netmap"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func Test_ValidateConfig(t *testing.T) {
|
||||
testArgs := make(map[string]any)
|
||||
|
||||
testArgs[netmap.MaxECDataCountConfig] = int64(11)
|
||||
require.Error(t, validateConfig(testArgs, false))
|
||||
|
||||
testArgs[netmap.MaxECParityCountConfig] = int64(256)
|
||||
require.Error(t, validateConfig(testArgs, false))
|
||||
require.NoError(t, validateConfig(testArgs, true))
|
||||
|
||||
testArgs[netmap.MaxECParityCountConfig] = int64(-1)
|
||||
require.Error(t, validateConfig(testArgs, false))
|
||||
|
||||
testArgs[netmap.MaxECParityCountConfig] = int64(55)
|
||||
require.NoError(t, validateConfig(testArgs, false))
|
||||
|
||||
testArgs[netmap.HomomorphicHashingDisabledKey] = "1"
|
||||
require.Error(t, validateConfig(testArgs, false))
|
||||
|
||||
testArgs[netmap.HomomorphicHashingDisabledKey] = true
|
||||
require.NoError(t, validateConfig(testArgs, false))
|
||||
|
||||
testArgs["not-well-known-configuration-key"] = "key"
|
||||
require.NoError(t, validateConfig(testArgs, false))
|
||||
}
|
46
cmd/frostfs-adm/internal/modules/morph/config/root.go
Normal file
46
cmd/frostfs-adm/internal/modules/morph/config/root.go
Normal file
|
@ -0,0 +1,46 @@
|
|||
package config
|
||||
|
||||
import (
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var (
|
||||
SetCmd = &cobra.Command{
|
||||
Use: "set-config key1=val1 [key2=val2 ...]",
|
||||
DisableFlagsInUseLine: true,
|
||||
Short: "Add/update global config value in the FrostFS network",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.AlphabetWalletsFlag, cmd.Flags().Lookup(commonflags.AlphabetWalletsFlag))
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
RunE: SetConfigCmd,
|
||||
}
|
||||
|
||||
DumpCmd = &cobra.Command{
|
||||
Use: "dump-config",
|
||||
Short: "Dump FrostFS network config",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
RunE: dumpNetworkConfig,
|
||||
}
|
||||
)
|
||||
|
||||
func initSetConfigCmd() {
|
||||
SetCmd.Flags().String(commonflags.AlphabetWalletsFlag, "", commonflags.AlphabetWalletsFlagDesc)
|
||||
SetCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
SetCmd.Flags().Bool(forceConfigSet, false, "Force setting not well-known configuration key")
|
||||
SetCmd.Flags().String(commonflags.LocalDumpFlag, "", "Path to the blocks dump file")
|
||||
}
|
||||
|
||||
func initDumpNetworkConfigCmd() {
|
||||
DumpCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
}
|
||||
|
||||
func init() {
|
||||
initSetConfigCmd()
|
||||
initDumpNetworkConfigCmd()
|
||||
}
|
59
cmd/frostfs-adm/internal/modules/morph/constants/const.go
Normal file
59
cmd/frostfs-adm/internal/modules/morph/constants/const.go
Normal file
|
@ -0,0 +1,59 @@
|
|||
package constants
|
||||
|
||||
import "time"
|
||||
|
||||
const (
|
||||
ConsensusAccountName = "consensus"
|
||||
|
||||
// MaxAlphabetNodes is the maximum number of candidates allowed, which is currently limited by the size
|
||||
// of the invocation script.
|
||||
// See: https://github.com/nspcc-dev/neo-go/blob/740488f7f35e367eaa99a71c0a609c315fe2b0fc/pkg/core/transaction/witness.go#L10
|
||||
MaxAlphabetNodes = 22
|
||||
|
||||
SingleAccountName = "single"
|
||||
CommitteeAccountName = "committee"
|
||||
|
||||
NNSContract = "nns"
|
||||
FrostfsContract = "frostfs" // not deployed in side-chain.
|
||||
ProcessingContract = "processing" // not deployed in side-chain.
|
||||
AlphabetContract = "alphabet"
|
||||
BalanceContract = "balance"
|
||||
ContainerContract = "container"
|
||||
FrostfsIDContract = "frostfsid"
|
||||
NetmapContract = "netmap"
|
||||
PolicyContract = "policy"
|
||||
ProxyContract = "proxy"
|
||||
|
||||
ContractWalletFilename = "contract.json"
|
||||
ContractWalletPasswordKey = "contract"
|
||||
|
||||
FrostfsOpsEmail = "ops@frostfs.info"
|
||||
NNSRefreshDefVal = int64(3600)
|
||||
NNSRetryDefVal = int64(600)
|
||||
NNSTtlDefVal = int64(3600)
|
||||
|
||||
DefaultExpirationTime = 10 * 365 * 24 * time.Hour / time.Second
|
||||
|
||||
DeployMethodName = "deploy"
|
||||
UpdateMethodName = "update"
|
||||
|
||||
TestContractPassword = "grouppass"
|
||||
)
|
||||
|
||||
var (
|
||||
ContractList = []string{
|
||||
BalanceContract,
|
||||
ContainerContract,
|
||||
FrostfsIDContract,
|
||||
NetmapContract,
|
||||
PolicyContract,
|
||||
ProxyContract,
|
||||
}
|
||||
|
||||
FullContractList = append([]string{
|
||||
FrostfsContract,
|
||||
ProcessingContract,
|
||||
NNSContract,
|
||||
AlphabetContract,
|
||||
}, ContractList...)
|
||||
)
|
|
@ -1,12 +1,15 @@
|
|||
package morph
|
||||
package container
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"slices"
|
||||
"sort"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/constants"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/helper"
|
||||
cid "git.frostfs.info/TrueCloudLab/frostfs-sdk-go/container/id"
|
||||
"github.com/nspcc-dev/neo-go/pkg/crypto/hash"
|
||||
"github.com/nspcc-dev/neo-go/pkg/io"
|
||||
|
@ -31,11 +34,11 @@ func getContainerContractHash(cmd *cobra.Command, inv *invoker.Invoker) (util.Ui
|
|||
}
|
||||
if err != nil {
|
||||
r := management.NewReader(inv)
|
||||
nnsCs, err := r.GetContractByID(1)
|
||||
nnsCs, err := helper.GetContractByID(r, 1)
|
||||
if err != nil {
|
||||
return util.Uint160{}, fmt.Errorf("can't get NNS contract state: %w", err)
|
||||
}
|
||||
ch, err = nnsResolveHash(inv, nnsCs.Hash, domainOf(containerContract))
|
||||
ch, err = helper.NNSResolveHash(inv, nnsCs.Hash, helper.DomainOf(constants.ContainerContract))
|
||||
if err != nil {
|
||||
return util.Uint160{}, err
|
||||
}
|
||||
|
@ -73,7 +76,7 @@ func dumpContainers(cmd *cobra.Command, _ []string) error {
|
|||
return fmt.Errorf("invalid filename: %w", err)
|
||||
}
|
||||
|
||||
c, err := getN3Client(viper.GetViper())
|
||||
c, err := helper.NewRemoteClient(viper.GetViper())
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't create N3 client: %w", err)
|
||||
}
|
||||
|
@ -136,13 +139,12 @@ func dumpContainers(cmd *cobra.Command, _ []string) error {
|
|||
func dumpSingleContainer(bw *io.BufBinWriter, ch util.Uint160, inv *invoker.Invoker, id []byte) (*Container, error) {
|
||||
bw.Reset()
|
||||
emit.AppCall(bw.BinWriter, ch, "get", callflag.All, id)
|
||||
emit.AppCall(bw.BinWriter, ch, "eACL", callflag.All, id)
|
||||
res, err := inv.Run(bw.Bytes())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't get container info: %w", err)
|
||||
}
|
||||
if len(res.Stack) != 2 {
|
||||
return nil, fmt.Errorf("%w: expected 2 items on stack", errInvalidContainerResponse)
|
||||
if len(res.Stack) != 1 {
|
||||
return nil, fmt.Errorf("%w: expected 1 items on stack", errInvalidContainerResponse)
|
||||
}
|
||||
|
||||
cnt := new(Container)
|
||||
|
@ -151,19 +153,11 @@ func dumpSingleContainer(bw *io.BufBinWriter, ch util.Uint160, inv *invoker.Invo
|
|||
return nil, fmt.Errorf("%w: %v", errInvalidContainerResponse, err)
|
||||
}
|
||||
|
||||
ea := new(EACL)
|
||||
err = ea.FromStackItem(res.Stack[1])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %v", errInvalidContainerResponse, err)
|
||||
}
|
||||
if len(ea.Value) != 0 {
|
||||
cnt.EACL = ea
|
||||
}
|
||||
return cnt, nil
|
||||
}
|
||||
|
||||
func listContainers(cmd *cobra.Command, _ []string) error {
|
||||
c, err := getN3Client(viper.GetViper())
|
||||
c, err := helper.NewRemoteClient(viper.GetViper())
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't create N3 client: %w", err)
|
||||
}
|
||||
|
@ -192,11 +186,11 @@ func restoreContainers(cmd *cobra.Command, _ []string) error {
|
|||
return fmt.Errorf("invalid filename: %w", err)
|
||||
}
|
||||
|
||||
wCtx, err := newInitializeContext(cmd, viper.GetViper())
|
||||
wCtx, err := helper.NewInitializeContext(cmd, viper.GetViper())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer wCtx.close()
|
||||
defer wCtx.Close()
|
||||
|
||||
containers, err := parseContainers(filename)
|
||||
if err != nil {
|
||||
|
@ -218,10 +212,10 @@ func restoreContainers(cmd *cobra.Command, _ []string) error {
|
|||
return err
|
||||
}
|
||||
|
||||
return wCtx.awaitTx()
|
||||
return wCtx.AwaitTx()
|
||||
}
|
||||
|
||||
func restoreOrPutContainers(containers []Container, isOK func([]byte) bool, cmd *cobra.Command, wCtx *initializeContext, ch util.Uint160) error {
|
||||
func restoreOrPutContainers(containers []Container, isOK func([]byte) bool, cmd *cobra.Command, wCtx *helper.InitializeContext, ch util.Uint160) error {
|
||||
bw := io.NewBufBinWriter()
|
||||
for _, cnt := range containers {
|
||||
hv := hash.Sha256(cnt.Value)
|
||||
|
@ -245,7 +239,7 @@ func restoreOrPutContainers(containers []Container, isOK func([]byte) bool, cmd
|
|||
panic(bw.Err)
|
||||
}
|
||||
|
||||
if err := wCtx.sendConsensusTx(bw.Bytes()); err != nil {
|
||||
if err := wCtx.SendConsensusTx(bw.Bytes()); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
@ -255,13 +249,9 @@ func restoreOrPutContainers(containers []Container, isOK func([]byte) bool, cmd
|
|||
func putContainer(bw *io.BufBinWriter, ch util.Uint160, cnt Container) {
|
||||
emit.AppCall(bw.BinWriter, ch, "put", callflag.All,
|
||||
cnt.Value, cnt.Signature, cnt.PublicKey, cnt.Token)
|
||||
if ea := cnt.EACL; ea != nil {
|
||||
emit.AppCall(bw.BinWriter, ch, "setEACL", callflag.All,
|
||||
ea.Value, ea.Signature, ea.PublicKey, ea.Token)
|
||||
}
|
||||
}
|
||||
|
||||
func isContainerRestored(cmd *cobra.Command, wCtx *initializeContext, containerHash util.Uint160, bw *io.BufBinWriter, hashValue util.Uint256) (bool, error) {
|
||||
func isContainerRestored(cmd *cobra.Command, wCtx *helper.InitializeContext, containerHash util.Uint160, bw *io.BufBinWriter, hashValue util.Uint256) (bool, error) {
|
||||
emit.AppCall(bw.BinWriter, containerHash, "get", callflag.All, hashValue.BytesBE())
|
||||
res, err := wCtx.Client.InvokeScript(bw.Bytes(), nil)
|
||||
if err != nil {
|
||||
|
@ -299,14 +289,14 @@ func parseContainers(filename string) ([]Container, error) {
|
|||
return containers, nil
|
||||
}
|
||||
|
||||
func fetchContainerContractHash(wCtx *initializeContext) (util.Uint160, error) {
|
||||
func fetchContainerContractHash(wCtx *helper.InitializeContext) (util.Uint160, error) {
|
||||
r := management.NewReader(wCtx.ReadOnlyInvoker)
|
||||
nnsCs, err := r.GetContractByID(1)
|
||||
nnsCs, err := helper.GetContractByID(r, 1)
|
||||
if err != nil {
|
||||
return util.Uint160{}, fmt.Errorf("can't get NNS contract state: %w", err)
|
||||
}
|
||||
|
||||
ch, err := nnsResolveHash(wCtx.ReadOnlyInvoker, nnsCs.Hash, domainOf(containerContract))
|
||||
ch, err := helper.NNSResolveHash(wCtx.ReadOnlyInvoker, nnsCs.Hash, helper.DomainOf(constants.ContainerContract))
|
||||
if err != nil {
|
||||
return util.Uint160{}, fmt.Errorf("can't fetch container contract hash: %w", err)
|
||||
}
|
||||
|
@ -319,15 +309,6 @@ type Container struct {
|
|||
Signature []byte `json:"signature"`
|
||||
PublicKey []byte `json:"public_key"`
|
||||
Token []byte `json:"token"`
|
||||
EACL *EACL `json:"eacl"`
|
||||
}
|
||||
|
||||
// EACL represents extended ACL struct in contract storage.
|
||||
type EACL struct {
|
||||
Value []byte `json:"value"`
|
||||
Signature []byte `json:"signature"`
|
||||
PublicKey []byte `json:"public_key"`
|
||||
Token []byte `json:"token"`
|
||||
}
|
||||
|
||||
// ToStackItem implements stackitem.Convertible.
|
||||
|
@ -374,50 +355,6 @@ func (c *Container) FromStackItem(item stackitem.Item) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
// ToStackItem implements stackitem.Convertible.
|
||||
func (c *EACL) ToStackItem() (stackitem.Item, error) {
|
||||
return stackitem.NewStruct([]stackitem.Item{
|
||||
stackitem.NewByteArray(c.Value),
|
||||
stackitem.NewByteArray(c.Signature),
|
||||
stackitem.NewByteArray(c.PublicKey),
|
||||
stackitem.NewByteArray(c.Token),
|
||||
}), nil
|
||||
}
|
||||
|
||||
// FromStackItem implements stackitem.Convertible.
|
||||
func (c *EACL) FromStackItem(item stackitem.Item) error {
|
||||
arr, ok := item.Value().([]stackitem.Item)
|
||||
if !ok || len(arr) != 4 {
|
||||
return errors.New("invalid stack item type")
|
||||
}
|
||||
|
||||
value, err := arr[0].TryBytes()
|
||||
if err != nil {
|
||||
return errors.New("invalid eACL value")
|
||||
}
|
||||
|
||||
sig, err := arr[1].TryBytes()
|
||||
if err != nil {
|
||||
return errors.New("invalid eACL signature")
|
||||
}
|
||||
|
||||
pub, err := arr[2].TryBytes()
|
||||
if err != nil {
|
||||
return errors.New("invalid eACL public key")
|
||||
}
|
||||
|
||||
tok, err := arr[3].TryBytes()
|
||||
if err != nil {
|
||||
return errors.New("invalid eACL token")
|
||||
}
|
||||
|
||||
c.Value = value
|
||||
c.Signature = sig
|
||||
c.PublicKey = pub
|
||||
c.Token = tok
|
||||
return nil
|
||||
}
|
||||
|
||||
// getCIDFilterFunc returns filtering function for container IDs.
|
||||
// Raw byte slices are used because it works with structures returned
|
||||
// from contract.
|
||||
|
@ -444,7 +381,7 @@ func getCIDFilterFunc(cmd *cobra.Command) (func([]byte) bool, error) {
|
|||
var id cid.ID
|
||||
id.SetSHA256(v)
|
||||
idStr := id.EncodeToString()
|
||||
n := sort.Search(len(rawIDs), func(i int) bool { return rawIDs[i] >= idStr })
|
||||
return n < len(rawIDs) && rawIDs[n] == idStr
|
||||
_, found := slices.BinarySearch(rawIDs, idStr)
|
||||
return found
|
||||
}, nil
|
||||
}
|
68
cmd/frostfs-adm/internal/modules/morph/container/root.go
Normal file
68
cmd/frostfs-adm/internal/modules/morph/container/root.go
Normal file
|
@ -0,0 +1,68 @@
|
|||
package container
|
||||
|
||||
import (
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
const (
|
||||
containerDumpFlag = "dump"
|
||||
containerContractFlag = "container-contract"
|
||||
containerIDsFlag = "cid"
|
||||
)
|
||||
|
||||
var (
|
||||
DumpCmd = &cobra.Command{
|
||||
Use: "dump-containers",
|
||||
Short: "Dump FrostFS containers to file",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
RunE: dumpContainers,
|
||||
}
|
||||
|
||||
RestoreCmd = &cobra.Command{
|
||||
Use: "restore-containers",
|
||||
Short: "Restore FrostFS containers from file",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.AlphabetWalletsFlag, cmd.Flags().Lookup(commonflags.AlphabetWalletsFlag))
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
RunE: restoreContainers,
|
||||
}
|
||||
|
||||
ListCmd = &cobra.Command{
|
||||
Use: "list-containers",
|
||||
Short: "List FrostFS containers",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
RunE: listContainers,
|
||||
}
|
||||
)
|
||||
|
||||
func initListContainersCmd() {
|
||||
ListCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
ListCmd.Flags().String(containerContractFlag, "", "Container contract hash (for networks without NNS)")
|
||||
}
|
||||
|
||||
func initRestoreContainersCmd() {
|
||||
RestoreCmd.Flags().String(commonflags.AlphabetWalletsFlag, "", commonflags.AlphabetWalletsFlagDesc)
|
||||
RestoreCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
RestoreCmd.Flags().String(containerDumpFlag, "", "File to restore containers from")
|
||||
RestoreCmd.Flags().StringSlice(containerIDsFlag, nil, "Containers to restore")
|
||||
}
|
||||
|
||||
func initDumpContainersCmd() {
|
||||
DumpCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
DumpCmd.Flags().String(containerDumpFlag, "", "File where to save dumped containers")
|
||||
DumpCmd.Flags().String(containerContractFlag, "", "Container contract hash (for networks without NNS)")
|
||||
DumpCmd.Flags().StringSlice(containerIDsFlag, nil, "Containers to dump")
|
||||
}
|
||||
|
||||
func init() {
|
||||
initDumpContainersCmd()
|
||||
initRestoreContainersCmd()
|
||||
initListContainersCmd()
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package morph
|
||||
package contract
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
@ -7,6 +7,9 @@ import (
|
|||
"strings"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-contract/nns"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/constants"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/helper"
|
||||
"github.com/nspcc-dev/neo-go/cli/cmdargs"
|
||||
"github.com/nspcc-dev/neo-go/pkg/core/state"
|
||||
"github.com/nspcc-dev/neo-go/pkg/encoding/address"
|
||||
|
@ -23,10 +26,9 @@ import (
|
|||
const (
|
||||
contractPathFlag = "contract"
|
||||
updateFlag = "update"
|
||||
customZoneFlag = "domain"
|
||||
)
|
||||
|
||||
var deployCmd = &cobra.Command{
|
||||
var DeployCmd = &cobra.Command{
|
||||
Use: "deploy",
|
||||
Short: "Deploy additional smart-contracts",
|
||||
Long: `Deploy additional smart-contract which are not related to core.
|
||||
|
@ -37,33 +39,33 @@ Compiled contract file name must contain '_contract.nef' suffix.
|
|||
Contract's manifest file name must be 'config.json'.
|
||||
NNS name is taken by stripping '_contract.nef' from the NEF file (similar to frostfs contracts).`,
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(alphabetWalletsFlag, cmd.Flags().Lookup(alphabetWalletsFlag))
|
||||
_ = viper.BindPFlag(endpointFlag, cmd.Flags().Lookup(endpointFlag))
|
||||
_ = viper.BindPFlag(commonflags.AlphabetWalletsFlag, cmd.Flags().Lookup(commonflags.AlphabetWalletsFlag))
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
RunE: deployContractCmd,
|
||||
}
|
||||
|
||||
func init() {
|
||||
ff := deployCmd.Flags()
|
||||
ff := DeployCmd.Flags()
|
||||
|
||||
ff.String(alphabetWalletsFlag, "", alphabetWalletsFlagDesc)
|
||||
_ = deployCmd.MarkFlagFilename(alphabetWalletsFlag)
|
||||
ff.String(commonflags.AlphabetWalletsFlag, "", commonflags.AlphabetWalletsFlagDesc)
|
||||
_ = DeployCmd.MarkFlagFilename(commonflags.AlphabetWalletsFlag)
|
||||
|
||||
ff.StringP(endpointFlag, "r", "", endpointFlagDesc)
|
||||
ff.StringP(commonflags.EndpointFlag, "r", "", commonflags.EndpointFlagDesc)
|
||||
ff.String(contractPathFlag, "", "Path to the contract directory")
|
||||
_ = deployCmd.MarkFlagFilename(contractPathFlag)
|
||||
_ = DeployCmd.MarkFlagFilename(contractPathFlag)
|
||||
|
||||
ff.Bool(updateFlag, false, "Update an existing contract")
|
||||
ff.String(customZoneFlag, "frostfs", "Custom zone for NNS")
|
||||
ff.String(commonflags.CustomZoneFlag, "frostfs", "Custom zone for NNS")
|
||||
}
|
||||
|
||||
func deployContractCmd(cmd *cobra.Command, args []string) error {
|
||||
v := viper.GetViper()
|
||||
c, err := newInitializeContext(cmd, v)
|
||||
c, err := helper.NewInitializeContext(cmd, v)
|
||||
if err != nil {
|
||||
return fmt.Errorf("initialization error: %w", err)
|
||||
}
|
||||
defer c.close()
|
||||
defer c.Close()
|
||||
|
||||
ctrPath, _ := cmd.Flags().GetString(contractPathFlag)
|
||||
ctrName, err := probeContractName(ctrPath)
|
||||
|
@ -71,29 +73,29 @@ func deployContractCmd(cmd *cobra.Command, args []string) error {
|
|||
return err
|
||||
}
|
||||
|
||||
cs, err := readContract(ctrPath, ctrName)
|
||||
cs, err := helper.ReadContract(ctrPath, ctrName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
r := management.NewReader(c.ReadOnlyInvoker)
|
||||
nnsCs, err := r.GetContractByID(1)
|
||||
nnsCs, err := helper.GetContractByID(r, 1)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't fetch NNS contract state: %w", err)
|
||||
}
|
||||
|
||||
callHash := management.Hash
|
||||
method := deployMethodName
|
||||
zone, _ := cmd.Flags().GetString(customZoneFlag)
|
||||
method := constants.DeployMethodName
|
||||
zone, _ := cmd.Flags().GetString(commonflags.CustomZoneFlag)
|
||||
domain := ctrName + "." + zone
|
||||
isUpdate, _ := cmd.Flags().GetBool(updateFlag)
|
||||
if isUpdate {
|
||||
cs.Hash, err = nnsResolveHash(c.ReadOnlyInvoker, nnsCs.Hash, domain)
|
||||
cs.Hash, err = helper.NNSResolveHash(c.ReadOnlyInvoker, nnsCs.Hash, domain)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't fetch contract hash from NNS: %w", err)
|
||||
}
|
||||
callHash = cs.Hash
|
||||
method = updateMethodName
|
||||
method = constants.UpdateMethodName
|
||||
} else {
|
||||
cs.Hash = state.CreateContractHash(
|
||||
c.CommitteeAcc.Contract.ScriptHash(),
|
||||
|
@ -122,13 +124,13 @@ func deployContractCmd(cmd *cobra.Command, args []string) error {
|
|||
panic(fmt.Errorf("BUG: can't create deployment script: %w", writer.Err))
|
||||
}
|
||||
|
||||
if err := c.sendCommitteeTx(writer.Bytes(), false); err != nil {
|
||||
if err := c.SendCommitteeTx(writer.Bytes(), false); err != nil {
|
||||
return err
|
||||
}
|
||||
return c.awaitTx()
|
||||
return c.AwaitTx()
|
||||
}
|
||||
|
||||
func registerNNS(nnsCs *state.Contract, c *initializeContext, zone string, domain string, cs *contractState, writer *io.BufBinWriter) error {
|
||||
func registerNNS(nnsCs *state.Contract, c *helper.InitializeContext, zone string, domain string, cs *helper.ContractState, writer *io.BufBinWriter) error {
|
||||
bw := io.NewBufBinWriter()
|
||||
emit.Instruction(bw.BinWriter, opcode.INITSSLOT, []byte{1})
|
||||
emit.AppCall(bw.BinWriter, nnsCs.Hash, "getPrice", callflag.All)
|
||||
|
@ -138,7 +140,7 @@ func registerNNS(nnsCs *state.Contract, c *initializeContext, zone string, domai
|
|||
start := bw.Len()
|
||||
needRecord := false
|
||||
|
||||
ok, err := c.nnsRootRegistered(nnsCs.Hash, zone)
|
||||
ok, err := c.NNSRootRegistered(nnsCs.Hash, zone)
|
||||
if err != nil {
|
||||
return err
|
||||
} else if !ok {
|
||||
|
@ -146,15 +148,17 @@ func registerNNS(nnsCs *state.Contract, c *initializeContext, zone string, domai
|
|||
|
||||
emit.AppCall(bw.BinWriter, nnsCs.Hash, "register", callflag.All,
|
||||
zone, c.CommitteeAcc.Contract.ScriptHash(),
|
||||
frostfsOpsEmail, int64(3600), int64(600), int64(defaultExpirationTime), int64(3600))
|
||||
constants.FrostfsOpsEmail, constants.NNSRefreshDefVal, constants.NNSRetryDefVal,
|
||||
int64(constants.DefaultExpirationTime), constants.NNSTtlDefVal)
|
||||
emit.Opcodes(bw.BinWriter, opcode.ASSERT)
|
||||
|
||||
emit.AppCall(bw.BinWriter, nnsCs.Hash, "register", callflag.All,
|
||||
domain, c.CommitteeAcc.Contract.ScriptHash(),
|
||||
frostfsOpsEmail, int64(3600), int64(600), int64(defaultExpirationTime), int64(3600))
|
||||
constants.FrostfsOpsEmail, constants.NNSRefreshDefVal, constants.NNSRetryDefVal,
|
||||
int64(constants.DefaultExpirationTime), constants.NNSTtlDefVal)
|
||||
emit.Opcodes(bw.BinWriter, opcode.ASSERT)
|
||||
} else {
|
||||
s, ok, err := c.nnsRegisterDomainScript(nnsCs.Hash, cs.Hash, domain)
|
||||
s, ok, err := c.NNSRegisterDomainScript(nnsCs.Hash, cs.Hash, domain)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package morph
|
||||
package contract
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
|
@ -8,6 +8,9 @@ import (
|
|||
"text/tabwriter"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-contract/nns"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/constants"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/helper"
|
||||
morphClient "git.frostfs.info/TrueCloudLab/frostfs-node/pkg/morph/client"
|
||||
"github.com/nspcc-dev/neo-go/pkg/io"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/invoker"
|
||||
|
@ -33,27 +36,27 @@ type contractDumpInfo struct {
|
|||
}
|
||||
|
||||
func dumpContractHashes(cmd *cobra.Command, _ []string) error {
|
||||
c, err := getN3Client(viper.GetViper())
|
||||
c, err := helper.NewRemoteClient(viper.GetViper())
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't create N3 client: %w", err)
|
||||
}
|
||||
|
||||
r := management.NewReader(invoker.New(c, nil))
|
||||
cs, err := r.GetContractByID(1)
|
||||
cs, err := helper.GetContractByID(r, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
zone, _ := cmd.Flags().GetString(customZoneFlag)
|
||||
zone, _ := cmd.Flags().GetString(commonflags.CustomZoneFlag)
|
||||
if zone != "" {
|
||||
return dumpCustomZoneHashes(cmd, cs.Hash, zone, c)
|
||||
}
|
||||
|
||||
infos := []contractDumpInfo{{name: nnsContract, hash: cs.Hash}}
|
||||
infos := []contractDumpInfo{{name: constants.NNSContract, hash: cs.Hash}}
|
||||
|
||||
irSize := 0
|
||||
for ; irSize < lastGlagoliticLetter; irSize++ {
|
||||
ok, err := nnsIsAvailable(c, cs.Hash, getAlphabetNNSDomain(irSize))
|
||||
ok, err := helper.NNSIsAvailable(c, cs.Hash, helper.GetAlphabetNNSDomain(irSize))
|
||||
if err != nil {
|
||||
return err
|
||||
} else if ok {
|
||||
|
@ -65,9 +68,9 @@ func dumpContractHashes(cmd *cobra.Command, _ []string) error {
|
|||
|
||||
if irSize != 0 {
|
||||
bw.Reset()
|
||||
for i := 0; i < irSize; i++ {
|
||||
for i := range irSize {
|
||||
emit.AppCall(bw.BinWriter, cs.Hash, "resolve", callflag.ReadOnly,
|
||||
getAlphabetNNSDomain(i),
|
||||
helper.GetAlphabetNNSDomain(i),
|
||||
int64(nns.TXT))
|
||||
}
|
||||
|
||||
|
@ -76,19 +79,19 @@ func dumpContractHashes(cmd *cobra.Command, _ []string) error {
|
|||
return fmt.Errorf("can't fetch info from NNS: %w", err)
|
||||
}
|
||||
|
||||
for i := 0; i < irSize; i++ {
|
||||
for i := range irSize {
|
||||
info := contractDumpInfo{name: fmt.Sprintf("alphabet %d", i)}
|
||||
if h, err := parseNNSResolveResult(alphaRes.Stack[i]); err == nil {
|
||||
if h, err := helper.ParseNNSResolveResult(alphaRes.Stack[i]); err == nil {
|
||||
info.hash = h
|
||||
}
|
||||
infos = append(infos, info)
|
||||
}
|
||||
}
|
||||
|
||||
for _, ctrName := range contractList {
|
||||
for _, ctrName := range constants.ContractList {
|
||||
bw.Reset()
|
||||
emit.AppCall(bw.BinWriter, cs.Hash, "resolve", callflag.ReadOnly,
|
||||
domainOf(ctrName), int64(nns.TXT))
|
||||
helper.DomainOf(ctrName), int64(nns.TXT))
|
||||
|
||||
res, err := c.InvokeScript(bw.Bytes(), nil)
|
||||
if err != nil {
|
||||
|
@ -97,7 +100,7 @@ func dumpContractHashes(cmd *cobra.Command, _ []string) error {
|
|||
|
||||
info := contractDumpInfo{name: ctrName}
|
||||
if len(res.Stack) != 0 {
|
||||
if h, err := parseNNSResolveResult(res.Stack[0]); err == nil {
|
||||
if h, err := helper.ParseNNSResolveResult(res.Stack[0]); err == nil {
|
||||
info.hash = h
|
||||
}
|
||||
}
|
||||
|
@ -110,7 +113,7 @@ func dumpContractHashes(cmd *cobra.Command, _ []string) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func dumpCustomZoneHashes(cmd *cobra.Command, nnsHash util.Uint160, zone string, c Client) error {
|
||||
func dumpCustomZoneHashes(cmd *cobra.Command, nnsHash util.Uint160, zone string, c helper.Client) error {
|
||||
const nnsMaxTokens = 100
|
||||
|
||||
inv := invoker.New(c, nil)
|
||||
|
@ -132,7 +135,7 @@ func dumpCustomZoneHashes(cmd *cobra.Command, nnsHash util.Uint160, zone string,
|
|||
return
|
||||
}
|
||||
|
||||
h, err := nnsResolveHash(inv, nnsHash, string(bs))
|
||||
h, err := helper.NNSResolveHash(inv, nnsHash, string(bs))
|
||||
if err != nil {
|
||||
cmd.PrintErrf("Could not resolve name %s: %v\n", string(bs), err)
|
||||
return
|
||||
|
@ -174,12 +177,12 @@ func dumpCustomZoneHashes(cmd *cobra.Command, nnsHash util.Uint160, zone string,
|
|||
_ = inv.TerminateSession(sessionID)
|
||||
}()
|
||||
|
||||
items, err := inv.TraverseIterator(sessionID, &iter, nnsMaxTokens)
|
||||
items, err := inv.TraverseIterator(sessionID, &iter, 0)
|
||||
for err == nil && len(items) != 0 {
|
||||
for i := range items {
|
||||
processItem(items[i])
|
||||
}
|
||||
items, err = inv.TraverseIterator(sessionID, &iter, nnsMaxTokens)
|
||||
items, err = inv.TraverseIterator(sessionID, &iter, 0)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("error during NNS domains iteration: %w", err)
|
||||
|
@ -224,7 +227,7 @@ func printContractInfo(cmd *cobra.Command, infos []contractDumpInfo) {
|
|||
cmd.Print(buf.String())
|
||||
}
|
||||
|
||||
func fillContractVersion(cmd *cobra.Command, c Client, infos []contractDumpInfo) {
|
||||
func fillContractVersion(cmd *cobra.Command, c helper.Client, infos []contractDumpInfo) {
|
||||
bw := io.NewBufBinWriter()
|
||||
sub := io.NewBufBinWriter()
|
||||
for i := range infos {
|
45
cmd/frostfs-adm/internal/modules/morph/contract/root.go
Normal file
45
cmd/frostfs-adm/internal/modules/morph/contract/root.go
Normal file
|
@ -0,0 +1,45 @@
|
|||
package contract
|
||||
|
||||
import (
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var (
|
||||
DumpHashesCmd = &cobra.Command{
|
||||
Use: "dump-hashes",
|
||||
Short: "Dump deployed contract hashes",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
RunE: dumpContractHashes,
|
||||
}
|
||||
UpdateCmd = &cobra.Command{
|
||||
Use: "update-contracts",
|
||||
Short: "Update FrostFS contracts",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.AlphabetWalletsFlag, cmd.Flags().Lookup(commonflags.AlphabetWalletsFlag))
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
RunE: updateContracts,
|
||||
}
|
||||
)
|
||||
|
||||
func initDumpContractHashesCmd() {
|
||||
DumpHashesCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
DumpHashesCmd.Flags().String(commonflags.CustomZoneFlag, "", "Custom zone to search.")
|
||||
}
|
||||
|
||||
func initUpdateContractsCmd() {
|
||||
UpdateCmd.Flags().String(commonflags.AlphabetWalletsFlag, "", commonflags.AlphabetWalletsFlagDesc)
|
||||
UpdateCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
UpdateCmd.Flags().String(commonflags.ContractsInitFlag, "", commonflags.ContractsInitFlagDesc)
|
||||
UpdateCmd.Flags().String(commonflags.ContractsURLFlag, "", commonflags.ContractsURLFlagDesc)
|
||||
UpdateCmd.MarkFlagsMutuallyExclusive(commonflags.ContractsInitFlag, commonflags.ContractsURLFlag)
|
||||
}
|
||||
|
||||
func init() {
|
||||
initDumpContractHashesCmd()
|
||||
initUpdateContractsCmd()
|
||||
}
|
197
cmd/frostfs-adm/internal/modules/morph/contract/update.go
Normal file
197
cmd/frostfs-adm/internal/modules/morph/contract/update.go
Normal file
|
@ -0,0 +1,197 @@
|
|||
package contract
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-contract/common"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-contract/nns"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/constants"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/helper"
|
||||
morphClient "git.frostfs.info/TrueCloudLab/frostfs-node/pkg/morph/client"
|
||||
"github.com/nspcc-dev/neo-go/pkg/encoding/address"
|
||||
io2 "github.com/nspcc-dev/neo-go/pkg/io"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/management"
|
||||
"github.com/nspcc-dev/neo-go/pkg/smartcontract/callflag"
|
||||
neoUtil "github.com/nspcc-dev/neo-go/pkg/util"
|
||||
"github.com/nspcc-dev/neo-go/pkg/vm/emit"
|
||||
"github.com/nspcc-dev/neo-go/pkg/vm/opcode"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var errMissingNNSRecord = errors.New("missing NNS record")
|
||||
|
||||
func updateContracts(cmd *cobra.Command, _ []string) error {
|
||||
wCtx, err := helper.NewInitializeContext(cmd, viper.GetViper())
|
||||
if err != nil {
|
||||
return fmt.Errorf("initialization error: %w", err)
|
||||
}
|
||||
|
||||
if err := helper.DeployNNS(wCtx, constants.UpdateMethodName); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return updateContractsInternal(wCtx)
|
||||
}
|
||||
|
||||
func updateContractsInternal(c *helper.InitializeContext) error {
|
||||
alphaCs := c.GetContract(constants.AlphabetContract)
|
||||
|
||||
nnsCs, err := c.NNSContractState()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
nnsHash := nnsCs.Hash
|
||||
|
||||
w := io2.NewBufBinWriter()
|
||||
|
||||
// Update script size for a single-node committee is close to the maximum allowed size of 65535.
|
||||
// Because of this we want to reuse alphabet contract NEF and manifest for different updates.
|
||||
// The generated script is as following.
|
||||
// 1. Initialize static slot for alphabet NEF.
|
||||
// 2. Store NEF into the static slot.
|
||||
// 3. Push parameters for each alphabet contract on stack.
|
||||
// 4. Add contract group to the manifest.
|
||||
// 5. For each alphabet contract, invoke `update` using parameters on stack and
|
||||
// NEF from step 2 and manifest from step 4.
|
||||
emit.Instruction(w.BinWriter, opcode.INITSSLOT, []byte{1})
|
||||
emit.Bytes(w.BinWriter, alphaCs.RawNEF)
|
||||
emit.Opcodes(w.BinWriter, opcode.STSFLD0)
|
||||
|
||||
keysParam, err := deployAlphabetAccounts(c, nnsHash, w, alphaCs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
w.Reset()
|
||||
|
||||
if err = deployOrUpdateContracts(c, w, nnsHash, keysParam); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
groupKey := c.ContractWallet.Accounts[0].PrivateKey().PublicKey()
|
||||
_, _, err = c.EmitUpdateNNSGroupScript(w, nnsHash, groupKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.Command.Printf("NNS: Set %s -> %s\n", morphClient.NNSGroupKeyName, hex.EncodeToString(groupKey.Bytes()))
|
||||
|
||||
emit.Opcodes(w.BinWriter, opcode.LDSFLD0)
|
||||
emit.Int(w.BinWriter, 1)
|
||||
emit.Opcodes(w.BinWriter, opcode.PACK)
|
||||
emit.AppCallNoArgs(w.BinWriter, nnsHash, "setPrice", callflag.All)
|
||||
|
||||
if err := c.SendCommitteeTx(w.Bytes(), false); err != nil {
|
||||
return err
|
||||
}
|
||||
return c.AwaitTx()
|
||||
}
|
||||
|
||||
func deployAlphabetAccounts(c *helper.InitializeContext, nnsHash neoUtil.Uint160, w *io2.BufBinWriter, alphaCs *helper.ContractState) ([]any, error) {
|
||||
var keysParam []any
|
||||
|
||||
baseGroups := alphaCs.Manifest.Groups
|
||||
|
||||
// alphabet contracts should be deployed by individual nodes to get different hashes.
|
||||
for i, acc := range c.Accounts {
|
||||
ctrHash, err := helper.NNSResolveHash(c.ReadOnlyInvoker, nnsHash, helper.GetAlphabetNNSDomain(i))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't resolve hash for contract update: %w", err)
|
||||
}
|
||||
|
||||
keysParam = append(keysParam, acc.PrivateKey().PublicKey().Bytes())
|
||||
|
||||
params := c.GetAlphabetDeployItems(i, len(c.Wallets))
|
||||
emit.Array(w.BinWriter, params...)
|
||||
|
||||
alphaCs.Manifest.Groups = baseGroups
|
||||
err = helper.AddManifestGroup(c.ContractWallet, ctrHash, alphaCs)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't sign manifest group: %v", err)
|
||||
}
|
||||
|
||||
emit.Bytes(w.BinWriter, alphaCs.RawManifest)
|
||||
emit.Opcodes(w.BinWriter, opcode.LDSFLD0)
|
||||
emit.Int(w.BinWriter, 3)
|
||||
emit.Opcodes(w.BinWriter, opcode.PACK)
|
||||
emit.AppCallNoArgs(w.BinWriter, ctrHash, constants.UpdateMethodName, callflag.All)
|
||||
}
|
||||
if err := c.SendCommitteeTx(w.Bytes(), false); err != nil {
|
||||
if !strings.Contains(err.Error(), common.ErrAlreadyUpdated) {
|
||||
return nil, err
|
||||
}
|
||||
c.Command.Println("Alphabet contracts are already updated.")
|
||||
}
|
||||
|
||||
return keysParam, nil
|
||||
}
|
||||
|
||||
func deployOrUpdateContracts(c *helper.InitializeContext, w *io2.BufBinWriter, nnsHash neoUtil.Uint160, keysParam []any) error {
|
||||
emit.Instruction(w.BinWriter, opcode.INITSSLOT, []byte{1})
|
||||
emit.AppCall(w.BinWriter, nnsHash, "getPrice", callflag.All)
|
||||
emit.Opcodes(w.BinWriter, opcode.STSFLD0)
|
||||
emit.AppCall(w.BinWriter, nnsHash, "setPrice", callflag.All, 1)
|
||||
|
||||
for _, ctrName := range constants.ContractList {
|
||||
cs := c.GetContract(ctrName)
|
||||
|
||||
method := constants.UpdateMethodName
|
||||
ctrHash, err := helper.NNSResolveHash(c.ReadOnlyInvoker, nnsHash, helper.DomainOf(ctrName))
|
||||
if err != nil {
|
||||
if errors.Is(err, errMissingNNSRecord) {
|
||||
// if contract not found we deploy it instead of update
|
||||
method = constants.DeployMethodName
|
||||
} else {
|
||||
return fmt.Errorf("can't resolve hash for contract update: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
err = helper.AddManifestGroup(c.ContractWallet, ctrHash, cs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't sign manifest group: %v", err)
|
||||
}
|
||||
|
||||
invokeHash := management.Hash
|
||||
if method == constants.UpdateMethodName {
|
||||
invokeHash = ctrHash
|
||||
}
|
||||
|
||||
args, err := helper.GetContractDeployData(c, ctrName, keysParam, constants.UpdateMethodName)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s: getting update params: %v", ctrName, err)
|
||||
}
|
||||
params := helper.GetContractDeployParameters(cs, args)
|
||||
res, err := c.CommitteeAct.MakeCall(invokeHash, method, params...)
|
||||
if err != nil {
|
||||
if method != constants.UpdateMethodName || !strings.Contains(err.Error(), common.ErrAlreadyUpdated) {
|
||||
return fmt.Errorf("deploy contract: %w", err)
|
||||
}
|
||||
c.Command.Printf("%s contract is already updated.\n", ctrName)
|
||||
continue
|
||||
}
|
||||
|
||||
w.WriteBytes(res.Script)
|
||||
|
||||
if method == constants.DeployMethodName {
|
||||
// same actions are done in InitializeContext.setNNS, can be unified
|
||||
domain := ctrName + ".frostfs"
|
||||
script, ok, err := c.NNSRegisterDomainScript(nnsHash, cs.Hash, domain)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
w.WriteBytes(script)
|
||||
emit.AppCall(w.BinWriter, nnsHash, "deleteRecords", callflag.All, domain, int64(nns.TXT))
|
||||
emit.AppCall(w.BinWriter, nnsHash, "addRecord", callflag.All,
|
||||
domain, int64(nns.TXT), cs.Hash.StringLE())
|
||||
emit.AppCall(w.BinWriter, nnsHash, "addRecord", callflag.All,
|
||||
domain, int64(nns.TXT), address.Uint160ToString(cs.Hash))
|
||||
}
|
||||
c.Command.Printf("NNS: Set %s -> %s\n", domain, cs.Hash.StringLE())
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
|
@ -1,67 +0,0 @@
|
|||
package morph
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/nspcc-dev/neo-go/pkg/io"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/management"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/unwrap"
|
||||
"github.com/nspcc-dev/neo-go/pkg/smartcontract/callflag"
|
||||
"github.com/nspcc-dev/neo-go/pkg/util"
|
||||
"github.com/nspcc-dev/neo-go/pkg/vm/emit"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
func forceNewEpochCmd(cmd *cobra.Command, _ []string) error {
|
||||
wCtx, err := newInitializeContext(cmd, viper.GetViper())
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't to initialize context: %w", err)
|
||||
}
|
||||
|
||||
r := management.NewReader(wCtx.ReadOnlyInvoker)
|
||||
cs, err := r.GetContractByID(1)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't get NNS contract info: %w", err)
|
||||
}
|
||||
|
||||
nmHash, err := nnsResolveHash(wCtx.ReadOnlyInvoker, cs.Hash, domainOf(netmapContract))
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't get netmap contract hash: %w", err)
|
||||
}
|
||||
|
||||
bw := io.NewBufBinWriter()
|
||||
if err := emitNewEpochCall(bw, wCtx, nmHash); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := wCtx.sendConsensusTx(bw.Bytes()); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := wCtx.awaitTx(); err != nil {
|
||||
if strings.Contains(err.Error(), "invalid epoch") {
|
||||
cmd.Println("Epoch has already ticked.")
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func emitNewEpochCall(bw *io.BufBinWriter, wCtx *initializeContext, nmHash util.Uint160) error {
|
||||
curr, err := unwrap.Int64(wCtx.ReadOnlyInvoker.Call(nmHash, "epoch"))
|
||||
if err != nil {
|
||||
return errors.New("can't fetch current epoch from the netmap contract")
|
||||
}
|
||||
|
||||
newEpoch := curr + 1
|
||||
wCtx.Command.Printf("Current epoch: %d, increase to %d.\n", curr, newEpoch)
|
||||
|
||||
// In NeoFS this is done via Notary contract. Here, however, we can form the
|
||||
// transaction locally.
|
||||
emit.AppCall(bw.BinWriter, nmHash, "newEpoch", callflag.All, newEpoch)
|
||||
return bw.Err
|
||||
}
|
|
@ -0,0 +1,83 @@
|
|||
package frostfsid
|
||||
|
||||
import (
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
commonCmd "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/internal/common"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var (
|
||||
frostfsidAddSubjectKeyCmd = &cobra.Command{
|
||||
Use: "add-subject-key",
|
||||
Short: "Add a public key to the subject in frostfsid contract",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.AlphabetWalletsFlag, cmd.Flags().Lookup(commonflags.AlphabetWalletsFlag))
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
Run: frostfsidAddSubjectKey,
|
||||
}
|
||||
frostfsidRemoveSubjectKeyCmd = &cobra.Command{
|
||||
Use: "remove-subject-key",
|
||||
Short: "Remove a public key from the subject in frostfsid contract",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.AlphabetWalletsFlag, cmd.Flags().Lookup(commonflags.AlphabetWalletsFlag))
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
Run: frostfsidRemoveSubjectKey,
|
||||
}
|
||||
)
|
||||
|
||||
func initFrostfsIDAddSubjectKeyCmd() {
|
||||
Cmd.AddCommand(frostfsidAddSubjectKeyCmd)
|
||||
|
||||
ff := frostfsidAddSubjectKeyCmd.Flags()
|
||||
ff.StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
ff.String(commonflags.AlphabetWalletsFlag, "", commonflags.AlphabetWalletsFlagDesc)
|
||||
|
||||
ff.String(subjectAddressFlag, "", "Subject address")
|
||||
_ = frostfsidAddSubjectKeyCmd.MarkFlagRequired(subjectAddressFlag)
|
||||
|
||||
ff.String(subjectKeyFlag, "", "Public key to add")
|
||||
_ = frostfsidAddSubjectKeyCmd.MarkFlagRequired(subjectKeyFlag)
|
||||
}
|
||||
|
||||
func initFrostfsIDRemoveSubjectKeyCmd() {
|
||||
Cmd.AddCommand(frostfsidRemoveSubjectKeyCmd)
|
||||
|
||||
ff := frostfsidRemoveSubjectKeyCmd.Flags()
|
||||
ff.StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
ff.String(commonflags.AlphabetWalletsFlag, "", commonflags.AlphabetWalletsFlagDesc)
|
||||
|
||||
ff.String(subjectAddressFlag, "", "Subject address")
|
||||
_ = frostfsidAddSubjectKeyCmd.MarkFlagRequired(subjectAddressFlag)
|
||||
|
||||
ff.String(subjectKeyFlag, "", "Public key to remove")
|
||||
_ = frostfsidAddSubjectKeyCmd.MarkFlagRequired(subjectKeyFlag)
|
||||
}
|
||||
|
||||
func frostfsidAddSubjectKey(cmd *cobra.Command, _ []string) {
|
||||
addr := getFrostfsIDSubjectAddress(cmd)
|
||||
pub := getFrostfsIDSubjectKey(cmd)
|
||||
|
||||
ffsid, err := newFrostfsIDClient(cmd)
|
||||
commonCmd.ExitOnErr(cmd, "init contract client: %w", err)
|
||||
|
||||
ffsid.addCall(ffsid.roCli.AddSubjectKeyCall(addr, pub))
|
||||
|
||||
err = ffsid.sendWait()
|
||||
commonCmd.ExitOnErr(cmd, "add subject key: %w", err)
|
||||
}
|
||||
|
||||
func frostfsidRemoveSubjectKey(cmd *cobra.Command, _ []string) {
|
||||
addr := getFrostfsIDSubjectAddress(cmd)
|
||||
pub := getFrostfsIDSubjectKey(cmd)
|
||||
|
||||
ffsid, err := newFrostfsIDClient(cmd)
|
||||
commonCmd.ExitOnErr(cmd, "init contract client: %w", err)
|
||||
|
||||
ffsid.addCall(ffsid.roCli.RemoveSubjectKeyCall(addr, pub))
|
||||
|
||||
err = ffsid.sendWait()
|
||||
commonCmd.ExitOnErr(cmd, "remove subject key: %w", err)
|
||||
}
|
|
@ -1,23 +1,33 @@
|
|||
package morph
|
||||
package frostfsid
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"sort"
|
||||
|
||||
frostfsidclient "git.frostfs.info/TrueCloudLab/frostfs-contract/frostfsid/client"
|
||||
frostfsidrpclient "git.frostfs.info/TrueCloudLab/frostfs-contract/rpcclient/frostfsid"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/constants"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/helper"
|
||||
commonCmd "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/internal/common"
|
||||
"github.com/google/uuid"
|
||||
"github.com/nspcc-dev/neo-go/pkg/core/state"
|
||||
"github.com/nspcc-dev/neo-go/pkg/encoding/address"
|
||||
"github.com/nspcc-dev/neo-go/pkg/io"
|
||||
"github.com/nspcc-dev/neo-go/pkg/neorpc/result"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/invoker"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/management"
|
||||
"github.com/nspcc-dev/neo-go/pkg/smartcontract/callflag"
|
||||
"github.com/nspcc-dev/neo-go/pkg/util"
|
||||
"github.com/nspcc-dev/neo-go/pkg/vm/emit"
|
||||
"github.com/nspcc-dev/neo-go/pkg/vm/stackitem"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
const iteratorBatchSize = 1
|
||||
|
||||
const (
|
||||
namespaceFlag = "namespace"
|
||||
subjectNameFlag = "subject-name"
|
||||
|
@ -26,12 +36,12 @@ const (
|
|||
includeNamesFlag = "include-names"
|
||||
groupNameFlag = "group-name"
|
||||
groupIDFlag = "group-id"
|
||||
|
||||
rootNamespacePlaceholder = "<root>"
|
||||
)
|
||||
|
||||
const rootNamespacePlaceholder = "<root>"
|
||||
|
||||
var (
|
||||
frostfsidCmd = &cobra.Command{
|
||||
Cmd = &cobra.Command{
|
||||
Use: "frostfsid",
|
||||
Short: "Section for frostfsid interactions commands",
|
||||
}
|
||||
|
@ -40,8 +50,8 @@ var (
|
|||
Use: "create-namespace",
|
||||
Short: "Create new namespace in frostfsid contract",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(alphabetWalletsFlag, cmd.Flags().Lookup(alphabetWalletsFlag))
|
||||
_ = viper.BindPFlag(endpointFlag, cmd.Flags().Lookup(endpointFlag))
|
||||
_ = viper.BindPFlag(commonflags.AlphabetWalletsFlag, cmd.Flags().Lookup(commonflags.AlphabetWalletsFlag))
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
Run: frostfsidCreateNamespace,
|
||||
}
|
||||
|
@ -50,8 +60,7 @@ var (
|
|||
Use: "list-namespaces",
|
||||
Short: "List all namespaces in frostfsid",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(alphabetWalletsFlag, cmd.Flags().Lookup(alphabetWalletsFlag))
|
||||
_ = viper.BindPFlag(endpointFlag, cmd.Flags().Lookup(endpointFlag))
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
Run: frostfsidListNamespaces,
|
||||
}
|
||||
|
@ -60,8 +69,8 @@ var (
|
|||
Use: "create-subject",
|
||||
Short: "Create subject in frostfsid contract",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(alphabetWalletsFlag, cmd.Flags().Lookup(alphabetWalletsFlag))
|
||||
_ = viper.BindPFlag(endpointFlag, cmd.Flags().Lookup(endpointFlag))
|
||||
_ = viper.BindPFlag(commonflags.AlphabetWalletsFlag, cmd.Flags().Lookup(commonflags.AlphabetWalletsFlag))
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
Run: frostfsidCreateSubject,
|
||||
}
|
||||
|
@ -70,8 +79,8 @@ var (
|
|||
Use: "delete-subject",
|
||||
Short: "Delete subject from frostfsid contract",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(alphabetWalletsFlag, cmd.Flags().Lookup(alphabetWalletsFlag))
|
||||
_ = viper.BindPFlag(endpointFlag, cmd.Flags().Lookup(endpointFlag))
|
||||
_ = viper.BindPFlag(commonflags.AlphabetWalletsFlag, cmd.Flags().Lookup(commonflags.AlphabetWalletsFlag))
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
Run: frostfsidDeleteSubject,
|
||||
}
|
||||
|
@ -80,8 +89,7 @@ var (
|
|||
Use: "list-subjects",
|
||||
Short: "List subjects in namespace",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(alphabetWalletsFlag, cmd.Flags().Lookup(alphabetWalletsFlag))
|
||||
_ = viper.BindPFlag(endpointFlag, cmd.Flags().Lookup(endpointFlag))
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
Run: frostfsidListSubjects,
|
||||
}
|
||||
|
@ -90,8 +98,8 @@ var (
|
|||
Use: "create-group",
|
||||
Short: "Create group in frostfsid contract",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(alphabetWalletsFlag, cmd.Flags().Lookup(alphabetWalletsFlag))
|
||||
_ = viper.BindPFlag(endpointFlag, cmd.Flags().Lookup(endpointFlag))
|
||||
_ = viper.BindPFlag(commonflags.AlphabetWalletsFlag, cmd.Flags().Lookup(commonflags.AlphabetWalletsFlag))
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
Run: frostfsidCreateGroup,
|
||||
}
|
||||
|
@ -100,8 +108,8 @@ var (
|
|||
Use: "delete-group",
|
||||
Short: "Delete group from frostfsid contract",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(alphabetWalletsFlag, cmd.Flags().Lookup(alphabetWalletsFlag))
|
||||
_ = viper.BindPFlag(endpointFlag, cmd.Flags().Lookup(endpointFlag))
|
||||
_ = viper.BindPFlag(commonflags.AlphabetWalletsFlag, cmd.Flags().Lookup(commonflags.AlphabetWalletsFlag))
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
Run: frostfsidDeleteGroup,
|
||||
}
|
||||
|
@ -110,8 +118,7 @@ var (
|
|||
Use: "list-groups",
|
||||
Short: "List groups in namespace",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(alphabetWalletsFlag, cmd.Flags().Lookup(alphabetWalletsFlag))
|
||||
_ = viper.BindPFlag(endpointFlag, cmd.Flags().Lookup(endpointFlag))
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
Run: frostfsidListGroups,
|
||||
}
|
||||
|
@ -120,8 +127,8 @@ var (
|
|||
Use: "add-subject-to-group",
|
||||
Short: "Add subject to group",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(alphabetWalletsFlag, cmd.Flags().Lookup(alphabetWalletsFlag))
|
||||
_ = viper.BindPFlag(endpointFlag, cmd.Flags().Lookup(endpointFlag))
|
||||
_ = viper.BindPFlag(commonflags.AlphabetWalletsFlag, cmd.Flags().Lookup(commonflags.AlphabetWalletsFlag))
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
Run: frostfsidAddSubjectToGroup,
|
||||
}
|
||||
|
@ -130,8 +137,8 @@ var (
|
|||
Use: "remove-subject-from-group",
|
||||
Short: "Remove subject from group",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(alphabetWalletsFlag, cmd.Flags().Lookup(alphabetWalletsFlag))
|
||||
_ = viper.BindPFlag(endpointFlag, cmd.Flags().Lookup(endpointFlag))
|
||||
_ = viper.BindPFlag(commonflags.AlphabetWalletsFlag, cmd.Flags().Lookup(commonflags.AlphabetWalletsFlag))
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
Run: frostfsidRemoveSubjectFromGroup,
|
||||
}
|
||||
|
@ -140,82 +147,90 @@ var (
|
|||
Use: "list-group-subjects",
|
||||
Short: "List subjects in group",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(alphabetWalletsFlag, cmd.Flags().Lookup(alphabetWalletsFlag))
|
||||
_ = viper.BindPFlag(endpointFlag, cmd.Flags().Lookup(endpointFlag))
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
Run: frostfsidListGroupSubjects,
|
||||
}
|
||||
)
|
||||
|
||||
func initFrostfsIDCreateNamespaceCmd() {
|
||||
frostfsidCmd.AddCommand(frostfsidCreateNamespaceCmd)
|
||||
frostfsidCreateNamespaceCmd.Flags().StringP(endpointFlag, endpointFlagShort, "", endpointFlagDesc)
|
||||
Cmd.AddCommand(frostfsidCreateNamespaceCmd)
|
||||
frostfsidCreateNamespaceCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
frostfsidCreateNamespaceCmd.Flags().String(namespaceFlag, "", "Namespace name to create")
|
||||
frostfsidCreateNamespaceCmd.Flags().String(commonflags.AlphabetWalletsFlag, "", commonflags.AlphabetWalletsFlagDesc)
|
||||
_ = frostfsidCreateNamespaceCmd.MarkFlagRequired(namespaceFlag)
|
||||
}
|
||||
|
||||
func initFrostfsIDListNamespacesCmd() {
|
||||
frostfsidCmd.AddCommand(frostfsidListNamespacesCmd)
|
||||
frostfsidListNamespacesCmd.Flags().StringP(endpointFlag, endpointFlagShort, "", endpointFlagDesc)
|
||||
Cmd.AddCommand(frostfsidListNamespacesCmd)
|
||||
frostfsidListNamespacesCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
}
|
||||
|
||||
func initFrostfsIDCreateSubjectCmd() {
|
||||
frostfsidCmd.AddCommand(frostfsidCreateSubjectCmd)
|
||||
frostfsidCreateSubjectCmd.Flags().StringP(endpointFlag, endpointFlagShort, "", endpointFlagDesc)
|
||||
Cmd.AddCommand(frostfsidCreateSubjectCmd)
|
||||
frostfsidCreateSubjectCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
frostfsidCreateSubjectCmd.Flags().String(namespaceFlag, "", "Namespace where create subject")
|
||||
frostfsidCreateSubjectCmd.Flags().String(subjectNameFlag, "", "Subject name, must be unique in namespace")
|
||||
frostfsidCreateSubjectCmd.Flags().String(subjectKeyFlag, "", "Subject hex-encoded public key")
|
||||
frostfsidCreateSubjectCmd.Flags().String(commonflags.AlphabetWalletsFlag, "", commonflags.AlphabetWalletsFlagDesc)
|
||||
}
|
||||
|
||||
func initFrostfsIDDeleteSubjectCmd() {
|
||||
frostfsidCmd.AddCommand(frostfsidDeleteSubjectCmd)
|
||||
frostfsidDeleteSubjectCmd.Flags().StringP(endpointFlag, endpointFlagShort, "", endpointFlagDesc)
|
||||
Cmd.AddCommand(frostfsidDeleteSubjectCmd)
|
||||
frostfsidDeleteSubjectCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
frostfsidDeleteSubjectCmd.Flags().String(subjectAddressFlag, "", "Subject address")
|
||||
frostfsidDeleteSubjectCmd.Flags().String(commonflags.AlphabetWalletsFlag, "", commonflags.AlphabetWalletsFlagDesc)
|
||||
}
|
||||
|
||||
func initFrostfsIDListSubjectsCmd() {
|
||||
frostfsidCmd.AddCommand(frostfsidListSubjectsCmd)
|
||||
frostfsidListSubjectsCmd.Flags().StringP(endpointFlag, endpointFlagShort, "", endpointFlagDesc)
|
||||
Cmd.AddCommand(frostfsidListSubjectsCmd)
|
||||
frostfsidListSubjectsCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
frostfsidListSubjectsCmd.Flags().String(namespaceFlag, "", "Namespace to list subjects")
|
||||
frostfsidListSubjectsCmd.Flags().Bool(includeNamesFlag, false, "Whether include subject name (require additional requests)")
|
||||
}
|
||||
|
||||
func initFrostfsIDCreateGroupCmd() {
|
||||
frostfsidCmd.AddCommand(frostfsidCreateGroupCmd)
|
||||
frostfsidCreateGroupCmd.Flags().StringP(endpointFlag, endpointFlagShort, "", endpointFlagDesc)
|
||||
Cmd.AddCommand(frostfsidCreateGroupCmd)
|
||||
frostfsidCreateGroupCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
frostfsidCreateGroupCmd.Flags().String(namespaceFlag, "", "Namespace where create group")
|
||||
frostfsidCreateGroupCmd.Flags().String(groupNameFlag, "", "Group name, must be unique in namespace")
|
||||
frostfsidCreateGroupCmd.Flags().String(commonflags.AlphabetWalletsFlag, "", commonflags.AlphabetWalletsFlagDesc)
|
||||
_ = frostfsidCreateGroupCmd.MarkFlagRequired(groupNameFlag)
|
||||
}
|
||||
|
||||
func initFrostfsIDDeleteGroupCmd() {
|
||||
frostfsidCmd.AddCommand(frostfsidDeleteGroupCmd)
|
||||
frostfsidDeleteGroupCmd.Flags().StringP(endpointFlag, endpointFlagShort, "", endpointFlagDesc)
|
||||
Cmd.AddCommand(frostfsidDeleteGroupCmd)
|
||||
frostfsidDeleteGroupCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
frostfsidDeleteGroupCmd.Flags().String(namespaceFlag, "", "Namespace to delete group")
|
||||
frostfsidDeleteGroupCmd.Flags().Int64(groupIDFlag, 0, "Group id")
|
||||
frostfsidDeleteGroupCmd.Flags().String(commonflags.AlphabetWalletsFlag, "", commonflags.AlphabetWalletsFlagDesc)
|
||||
}
|
||||
|
||||
func initFrostfsIDListGroupsCmd() {
|
||||
frostfsidCmd.AddCommand(frostfsidListGroupsCmd)
|
||||
frostfsidListGroupsCmd.Flags().StringP(endpointFlag, endpointFlagShort, "", endpointFlagDesc)
|
||||
Cmd.AddCommand(frostfsidListGroupsCmd)
|
||||
frostfsidListGroupsCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
frostfsidListGroupsCmd.Flags().String(namespaceFlag, "", "Namespace to list groups")
|
||||
}
|
||||
|
||||
func initFrostfsIDAddSubjectToGroupCmd() {
|
||||
frostfsidCmd.AddCommand(frostfsidAddSubjectToGroupCmd)
|
||||
frostfsidAddSubjectToGroupCmd.Flags().StringP(endpointFlag, endpointFlagShort, "", endpointFlagDesc)
|
||||
Cmd.AddCommand(frostfsidAddSubjectToGroupCmd)
|
||||
frostfsidAddSubjectToGroupCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
frostfsidAddSubjectToGroupCmd.Flags().String(subjectAddressFlag, "", "Subject address")
|
||||
frostfsidAddSubjectToGroupCmd.Flags().Int64(groupIDFlag, 0, "Group id")
|
||||
frostfsidAddSubjectToGroupCmd.Flags().String(commonflags.AlphabetWalletsFlag, "", commonflags.AlphabetWalletsFlagDesc)
|
||||
}
|
||||
|
||||
func initFrostfsIDRemoveSubjectFromGroupCmd() {
|
||||
frostfsidCmd.AddCommand(frostfsidRemoveSubjectFromGroupCmd)
|
||||
frostfsidRemoveSubjectFromGroupCmd.Flags().StringP(endpointFlag, endpointFlagShort, "", endpointFlagDesc)
|
||||
Cmd.AddCommand(frostfsidRemoveSubjectFromGroupCmd)
|
||||
frostfsidRemoveSubjectFromGroupCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
frostfsidRemoveSubjectFromGroupCmd.Flags().String(subjectAddressFlag, "", "Subject address")
|
||||
frostfsidRemoveSubjectFromGroupCmd.Flags().Int64(groupIDFlag, 0, "Group id")
|
||||
frostfsidRemoveSubjectFromGroupCmd.Flags().String(commonflags.AlphabetWalletsFlag, "", commonflags.AlphabetWalletsFlagDesc)
|
||||
}
|
||||
|
||||
func initFrostfsIDListGroupSubjectsCmd() {
|
||||
frostfsidCmd.AddCommand(frostfsidListGroupSubjectsCmd)
|
||||
frostfsidListGroupSubjectsCmd.Flags().StringP(endpointFlag, endpointFlagShort, "", endpointFlagDesc)
|
||||
Cmd.AddCommand(frostfsidListGroupSubjectsCmd)
|
||||
frostfsidListGroupSubjectsCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
frostfsidListGroupSubjectsCmd.Flags().String(namespaceFlag, "", "Namespace name")
|
||||
frostfsidListGroupSubjectsCmd.Flags().Int64(groupIDFlag, 0, "Group id")
|
||||
frostfsidListGroupSubjectsCmd.Flags().Bool(includeNamesFlag, false, "Whether include subject name (require additional requests)")
|
||||
|
@ -234,12 +249,15 @@ func frostfsidCreateNamespace(cmd *cobra.Command, _ []string) {
|
|||
}
|
||||
|
||||
func frostfsidListNamespaces(cmd *cobra.Command, _ []string) {
|
||||
ffsid, err := newFrostfsIDClient(cmd)
|
||||
commonCmd.ExitOnErr(cmd, "init contract invoker: %w", err)
|
||||
|
||||
namespaces, err := ffsid.roCli.ListNamespaces()
|
||||
commonCmd.ExitOnErr(cmd, "list namespaces: %w", err)
|
||||
inv, _, hash := initInvoker(cmd)
|
||||
reader := frostfsidrpclient.NewReader(inv, hash)
|
||||
sessionID, it, err := reader.ListNamespaces()
|
||||
commonCmd.ExitOnErr(cmd, "can't get namespace: %w", err)
|
||||
items, err := readIterator(inv, &it, iteratorBatchSize, sessionID)
|
||||
commonCmd.ExitOnErr(cmd, "can't read iterator: %w", err)
|
||||
|
||||
namespaces, err := frostfsidclient.ParseNamespaces(items)
|
||||
commonCmd.ExitOnErr(cmd, "can't parse namespace: %w", err)
|
||||
sort.Slice(namespaces, func(i, j int) bool { return namespaces[i].Name < namespaces[j].Name })
|
||||
|
||||
for _, namespace := range namespaces {
|
||||
|
@ -280,14 +298,15 @@ func frostfsidDeleteSubject(cmd *cobra.Command, _ []string) {
|
|||
}
|
||||
|
||||
func frostfsidListSubjects(cmd *cobra.Command, _ []string) {
|
||||
ns := getFrostfsIDNamespace(cmd)
|
||||
includeNames, _ := cmd.Flags().GetBool(includeNamesFlag)
|
||||
ns := getFrostfsIDNamespace(cmd)
|
||||
inv, _, hash := initInvoker(cmd)
|
||||
reader := frostfsidrpclient.NewReader(inv, hash)
|
||||
sessionID, it, err := reader.ListNamespaceSubjects(ns)
|
||||
commonCmd.ExitOnErr(cmd, "can't get namespace: %w", err)
|
||||
|
||||
ffsid, err := newFrostfsIDClient(cmd)
|
||||
commonCmd.ExitOnErr(cmd, "init contract invoker: %w", err)
|
||||
|
||||
subAddresses, err := ffsid.roCli.ListNamespaceSubjects(ns)
|
||||
commonCmd.ExitOnErr(cmd, "list subjects: %w", err)
|
||||
subAddresses, err := frostfsidclient.UnwrapArrayOfUint160(readIterator(inv, &it, iteratorBatchSize, sessionID))
|
||||
commonCmd.ExitOnErr(cmd, "can't unwrap: %w", err)
|
||||
|
||||
sort.Slice(subAddresses, func(i, j int) bool { return subAddresses[i].Less(subAddresses[j]) })
|
||||
|
||||
|
@ -297,8 +316,14 @@ func frostfsidListSubjects(cmd *cobra.Command, _ []string) {
|
|||
continue
|
||||
}
|
||||
|
||||
subj, err := ffsid.roCli.GetSubject(addr)
|
||||
commonCmd.ExitOnErr(cmd, "get subject: %w", err)
|
||||
sessionID, it, err := reader.ListSubjects()
|
||||
commonCmd.ExitOnErr(cmd, "can't get subject: %w", err)
|
||||
|
||||
items, err := readIterator(inv, &it, iteratorBatchSize, sessionID)
|
||||
commonCmd.ExitOnErr(cmd, "can't read iterator: %w", err)
|
||||
|
||||
subj, err := frostfsidclient.ParseSubject(items)
|
||||
commonCmd.ExitOnErr(cmd, "can't parse subject: %w", err)
|
||||
|
||||
cmd.Printf("%s (%s)\n", address.Uint160ToString(addr), subj.Name)
|
||||
}
|
||||
|
@ -333,13 +358,17 @@ func frostfsidDeleteGroup(cmd *cobra.Command, _ []string) {
|
|||
}
|
||||
|
||||
func frostfsidListGroups(cmd *cobra.Command, _ []string) {
|
||||
inv, _, hash := initInvoker(cmd)
|
||||
ns := getFrostfsIDNamespace(cmd)
|
||||
|
||||
ffsid, err := newFrostfsIDClient(cmd)
|
||||
commonCmd.ExitOnErr(cmd, "init contract invoker: %w", err)
|
||||
reader := frostfsidrpclient.NewReader(inv, hash)
|
||||
sessionID, it, err := reader.ListGroups(ns)
|
||||
commonCmd.ExitOnErr(cmd, "can't get namespace: %w", err)
|
||||
|
||||
groups, err := ffsid.roCli.ListGroups(ns)
|
||||
commonCmd.ExitOnErr(cmd, "list groups: %w", err)
|
||||
items, err := readIterator(inv, &it, iteratorBatchSize, sessionID)
|
||||
commonCmd.ExitOnErr(cmd, "can't list groups: %w", err)
|
||||
groups, err := frostfsidclient.ParseGroups(items)
|
||||
commonCmd.ExitOnErr(cmd, "can't parse groups: %w", err)
|
||||
|
||||
sort.Slice(groups, func(i, j int) bool { return groups[i].Name < groups[j].Name })
|
||||
|
||||
|
@ -378,12 +407,19 @@ func frostfsidListGroupSubjects(cmd *cobra.Command, _ []string) {
|
|||
ns := getFrostfsIDNamespace(cmd)
|
||||
groupID := getFrostfsIDGroupID(cmd)
|
||||
includeNames, _ := cmd.Flags().GetBool(includeNamesFlag)
|
||||
inv, cs, hash := initInvoker(cmd)
|
||||
_, err := helper.NNSResolveHash(inv, cs.Hash, helper.DomainOf(constants.FrostfsIDContract))
|
||||
commonCmd.ExitOnErr(cmd, "can't get netmap contract hash: %w", err)
|
||||
|
||||
ffsid, err := newFrostfsIDClient(cmd)
|
||||
commonCmd.ExitOnErr(cmd, "init contract client: %w", err)
|
||||
reader := frostfsidrpclient.NewReader(inv, hash)
|
||||
sessionID, it, err := reader.ListGroupSubjects(ns, big.NewInt(groupID))
|
||||
commonCmd.ExitOnErr(cmd, "can't list groups: %w", err)
|
||||
|
||||
subjects, err := ffsid.roCli.ListGroupSubjects(ns, groupID)
|
||||
commonCmd.ExitOnErr(cmd, "list group subjects: %w", err)
|
||||
items, err := readIterator(inv, &it, iteratorBatchSize, sessionID)
|
||||
commonCmd.ExitOnErr(cmd, "can't read iterator: %w", err)
|
||||
|
||||
subjects, err := frostfsidclient.UnwrapArrayOfUint160(items, err)
|
||||
commonCmd.ExitOnErr(cmd, "can't unwrap: %w", err)
|
||||
|
||||
sort.Slice(subjects, func(i, j int) bool { return subjects[i].Less(subjects[j]) })
|
||||
|
||||
|
@ -393,9 +429,10 @@ func frostfsidListGroupSubjects(cmd *cobra.Command, _ []string) {
|
|||
continue
|
||||
}
|
||||
|
||||
subj, err := ffsid.roCli.GetSubject(subjAddr)
|
||||
commonCmd.ExitOnErr(cmd, "get subject: %w", err)
|
||||
|
||||
items, err := reader.GetSubject(subjAddr)
|
||||
commonCmd.ExitOnErr(cmd, "can't get subject: %w", err)
|
||||
subj, err := frostfsidclient.ParseSubject(items)
|
||||
commonCmd.ExitOnErr(cmd, "can't parse subject: %w", err)
|
||||
cmd.Printf("%s (%s)\n", address.Uint160ToString(subjAddr), subj.Name)
|
||||
}
|
||||
}
|
||||
|
@ -404,22 +441,22 @@ type frostfsidClient struct {
|
|||
bw *io.BufBinWriter
|
||||
contractHash util.Uint160
|
||||
roCli *frostfsidclient.Client // client can be used only for waiting tx, parsing and forming method params
|
||||
wCtx *initializeContext
|
||||
wCtx *helper.InitializeContext
|
||||
}
|
||||
|
||||
func newFrostfsIDClient(cmd *cobra.Command) (*frostfsidClient, error) {
|
||||
wCtx, err := newInitializeContext(cmd, viper.GetViper())
|
||||
wCtx, err := helper.NewInitializeContext(cmd, viper.GetViper())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't to initialize context: %w", err)
|
||||
return nil, fmt.Errorf("can't initialize context: %w", err)
|
||||
}
|
||||
|
||||
r := management.NewReader(wCtx.ReadOnlyInvoker)
|
||||
cs, err := r.GetContractByID(1)
|
||||
cs, err := helper.GetContractByID(r, 1)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't get NNS contract info: %w", err)
|
||||
}
|
||||
|
||||
ffsidHash, err := nnsResolveHash(wCtx.ReadOnlyInvoker, cs.Hash, domainOf(frostfsIDContract))
|
||||
ffsidHash, err := helper.NNSResolveHash(wCtx.ReadOnlyInvoker, cs.Hash, helper.DomainOf(constants.FrostfsIDContract))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't get proxy contract hash: %w", err)
|
||||
}
|
||||
|
@ -437,24 +474,52 @@ func (f *frostfsidClient) addCall(method string, args []any) {
|
|||
}
|
||||
|
||||
func (f *frostfsidClient) sendWait() error {
|
||||
if err := f.wCtx.sendConsensusTx(f.bw.Bytes()); err != nil {
|
||||
if err := f.wCtx.SendConsensusTx(f.bw.Bytes()); err != nil {
|
||||
return err
|
||||
}
|
||||
f.bw.Reset()
|
||||
|
||||
return f.wCtx.awaitTx()
|
||||
return f.wCtx.AwaitTx()
|
||||
}
|
||||
|
||||
func (f *frostfsidClient) sendWaitRes() (*state.AppExecResult, error) {
|
||||
if err := f.wCtx.sendConsensusTx(f.bw.Bytes()); err != nil {
|
||||
if err := f.wCtx.SendConsensusTx(f.bw.Bytes()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f.bw.Reset()
|
||||
|
||||
if len(f.wCtx.SentTxs) == 0 {
|
||||
return nil, errors.New("no transactions to wait")
|
||||
f.wCtx.Command.Println("Waiting for transactions to persist...")
|
||||
return f.roCli.Wait(f.wCtx.SentTxs[0].Hash, f.wCtx.SentTxs[0].Vub, nil)
|
||||
}
|
||||
|
||||
func readIterator(inv *invoker.Invoker, iter *result.Iterator, batchSize int, sessionID uuid.UUID) ([]stackitem.Item, error) {
|
||||
var shouldStop bool
|
||||
res := make([]stackitem.Item, 0)
|
||||
for !shouldStop {
|
||||
items, err := inv.TraverseIterator(sessionID, iter, batchSize)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
res = append(res, items...)
|
||||
shouldStop = len(items) < batchSize
|
||||
}
|
||||
|
||||
f.wCtx.Command.Println("Waiting for transactions to persist...")
|
||||
return f.roCli.Wait(f.wCtx.SentTxs[0].hash, f.wCtx.SentTxs[0].vub, nil)
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func initInvoker(cmd *cobra.Command) (*invoker.Invoker, *state.Contract, util.Uint160) {
|
||||
c, err := helper.NewRemoteClient(viper.GetViper())
|
||||
commonCmd.ExitOnErr(cmd, "can't create N3 client: %w", err)
|
||||
|
||||
inv := invoker.New(c, nil)
|
||||
r := management.NewReader(inv)
|
||||
|
||||
cs, err := r.GetContractByID(1)
|
||||
commonCmd.ExitOnErr(cmd, "can't get NNS contract info: %w", err)
|
||||
|
||||
nmHash, err := helper.NNSResolveHash(inv, cs.Hash, helper.DomainOf(constants.FrostfsIDContract))
|
||||
commonCmd.ExitOnErr(cmd, "can't get netmap contract hash: %w", err)
|
||||
|
||||
return inv, cs, nmHash
|
||||
}
|
|
@ -1,49 +1,17 @@
|
|||
package morph
|
||||
package frostfsid
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
|
||||
commonCmd "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/internal/common"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/internal/ape"
|
||||
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
|
||||
"github.com/nspcc-dev/neo-go/pkg/encoding/address"
|
||||
"github.com/nspcc-dev/neo-go/pkg/util"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var (
|
||||
frostfsidSubjectNameRegexp = regexp.MustCompile(`^[\w+=,.@-]{1,64}$`)
|
||||
frostfsidGroupNameRegexp = regexp.MustCompile(`^[\w+=,.@-]{1,128}$`)
|
||||
|
||||
// frostfsidNamespaceNameRegexp similar to https://git.frostfs.info/TrueCloudLab/frostfs-contract/src/commit/f2a82aa635aa57d9b05092d8cf15b170b53cc324/nns/nns_contract.go#L690
|
||||
frostfsidNamespaceNameRegexp = regexp.MustCompile(`(^$)|(^[a-z0-9]{1,2}$)|(^[a-z0-9][a-z0-9-]{1,48}[a-z0-9]$)`)
|
||||
)
|
||||
|
||||
func getFrostfsIDAdmin(v *viper.Viper) (util.Uint160, bool, error) {
|
||||
admin := v.GetString(frostfsIDAdminConfigKey)
|
||||
if admin == "" {
|
||||
return util.Uint160{}, false, nil
|
||||
}
|
||||
|
||||
h, err := address.StringToUint160(admin)
|
||||
if err == nil {
|
||||
return h, true, nil
|
||||
}
|
||||
|
||||
h, err = util.Uint160DecodeStringLE(admin)
|
||||
if err == nil {
|
||||
return h, true, nil
|
||||
}
|
||||
|
||||
pk, err := keys.NewPublicKeyFromString(admin)
|
||||
if err == nil {
|
||||
return pk.GetScriptHash(), true, nil
|
||||
}
|
||||
return util.Uint160{}, true, fmt.Errorf("frostfsid: admin is invalid: '%s'", admin)
|
||||
}
|
||||
|
||||
func getFrostfsIDSubjectKey(cmd *cobra.Command) *keys.PublicKey {
|
||||
subjKeyHex, _ := cmd.Flags().GetString(subjectKeyFlag)
|
||||
subjKey, err := keys.NewPublicKeyFromString(subjKeyHex)
|
||||
|
@ -65,9 +33,9 @@ func getFrostfsIDSubjectName(cmd *cobra.Command) string {
|
|||
return ""
|
||||
}
|
||||
|
||||
if !frostfsidSubjectNameRegexp.MatchString(subjectName) {
|
||||
if !ape.SubjectNameRegexp.MatchString(subjectName) {
|
||||
commonCmd.ExitOnErr(cmd, "invalid subject name: %w",
|
||||
fmt.Errorf("name must match regexp: %s", frostfsidSubjectNameRegexp.String()))
|
||||
fmt.Errorf("name must match regexp: %s", ape.SubjectNameRegexp.String()))
|
||||
}
|
||||
|
||||
return subjectName
|
||||
|
@ -76,9 +44,9 @@ func getFrostfsIDSubjectName(cmd *cobra.Command) string {
|
|||
func getFrostfsIDGroupName(cmd *cobra.Command) string {
|
||||
groupName, _ := cmd.Flags().GetString(groupNameFlag)
|
||||
|
||||
if !frostfsidGroupNameRegexp.MatchString(groupName) {
|
||||
if !ape.GroupNameRegexp.MatchString(groupName) {
|
||||
commonCmd.ExitOnErr(cmd, "invalid group name: %w",
|
||||
fmt.Errorf("name must match regexp: %s", frostfsidGroupNameRegexp.String()))
|
||||
fmt.Errorf("name must match regexp: %s", ape.GroupNameRegexp.String()))
|
||||
}
|
||||
|
||||
return groupName
|
||||
|
@ -100,9 +68,9 @@ func getFrostfsIDNamespace(cmd *cobra.Command) string {
|
|||
ns = ""
|
||||
}
|
||||
|
||||
if !frostfsidNamespaceNameRegexp.MatchString(ns) {
|
||||
if !ape.NamespaceNameRegexp.MatchString(ns) {
|
||||
commonCmd.ExitOnErr(cmd, "invalid namespace: %w",
|
||||
fmt.Errorf("name must match regexp: %s", frostfsidNamespaceNameRegexp.String()))
|
||||
fmt.Errorf("name must match regexp: %s", ape.NamespaceNameRegexp.String()))
|
||||
}
|
||||
|
||||
return ns
|
|
@ -1,57 +1,12 @@
|
|||
package morph
|
||||
package frostfsid
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"testing"
|
||||
|
||||
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
|
||||
"github.com/nspcc-dev/neo-go/pkg/encoding/address"
|
||||
"github.com/spf13/viper"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/internal/ape"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestFrostfsIDConfig(t *testing.T) {
|
||||
pks := make([]*keys.PrivateKey, 4)
|
||||
for i := range pks {
|
||||
pk, err := keys.NewPrivateKey()
|
||||
require.NoError(t, err)
|
||||
pks[i] = pk
|
||||
}
|
||||
|
||||
fmts := []string{
|
||||
pks[0].GetScriptHash().StringLE(),
|
||||
address.Uint160ToString(pks[1].GetScriptHash()),
|
||||
hex.EncodeToString(pks[2].PublicKey().UncompressedBytes()),
|
||||
hex.EncodeToString(pks[3].PublicKey().Bytes()),
|
||||
}
|
||||
|
||||
for i := range fmts {
|
||||
v := viper.New()
|
||||
v.Set("frostfsid.admin", fmts[i])
|
||||
|
||||
actual, found, err := getFrostfsIDAdmin(v)
|
||||
require.NoError(t, err)
|
||||
require.True(t, found)
|
||||
require.Equal(t, pks[i].GetScriptHash(), actual)
|
||||
}
|
||||
|
||||
t.Run("bad key", func(t *testing.T) {
|
||||
v := viper.New()
|
||||
v.Set("frostfsid.admin", "abc")
|
||||
|
||||
_, found, err := getFrostfsIDAdmin(v)
|
||||
require.Error(t, err)
|
||||
require.True(t, found)
|
||||
})
|
||||
t.Run("missing key", func(t *testing.T) {
|
||||
v := viper.New()
|
||||
|
||||
_, found, err := getFrostfsIDAdmin(v)
|
||||
require.NoError(t, err)
|
||||
require.False(t, found)
|
||||
})
|
||||
}
|
||||
|
||||
func TestNamespaceRegexp(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
|
@ -95,7 +50,7 @@ func TestNamespaceRegexp(t *testing.T) {
|
|||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
require.Equal(t, tc.matched, frostfsidNamespaceNameRegexp.MatchString(tc.namespace))
|
||||
require.Equal(t, tc.matched, ape.NamespaceNameRegexp.MatchString(tc.namespace))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
@ -128,7 +83,7 @@ func TestSubjectNameRegexp(t *testing.T) {
|
|||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
require.Equal(t, tc.matched, frostfsidSubjectNameRegexp.MatchString(tc.subject))
|
||||
require.Equal(t, tc.matched, ape.SubjectNameRegexp.MatchString(tc.subject))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
@ -166,7 +121,7 @@ func TestSubjectGroupRegexp(t *testing.T) {
|
|||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
require.Equal(t, tc.matched, frostfsidGroupNameRegexp.MatchString(tc.subject))
|
||||
require.Equal(t, tc.matched, ape.GroupNameRegexp.MatchString(tc.subject))
|
||||
})
|
||||
}
|
||||
}
|
17
cmd/frostfs-adm/internal/modules/morph/frostfsid/root.go
Normal file
17
cmd/frostfs-adm/internal/modules/morph/frostfsid/root.go
Normal file
|
@ -0,0 +1,17 @@
|
|||
package frostfsid
|
||||
|
||||
func init() {
|
||||
initFrostfsIDCreateNamespaceCmd()
|
||||
initFrostfsIDListNamespacesCmd()
|
||||
initFrostfsIDCreateSubjectCmd()
|
||||
initFrostfsIDDeleteSubjectCmd()
|
||||
initFrostfsIDListSubjectsCmd()
|
||||
initFrostfsIDCreateGroupCmd()
|
||||
initFrostfsIDDeleteGroupCmd()
|
||||
initFrostfsIDListGroupsCmd()
|
||||
initFrostfsIDAddSubjectToGroupCmd()
|
||||
initFrostfsIDRemoveSubjectFromGroupCmd()
|
||||
initFrostfsIDListGroupSubjectsCmd()
|
||||
initFrostfsIDAddSubjectKeyCmd()
|
||||
initFrostfsIDRemoveSubjectKeyCmd()
|
||||
}
|
|
@ -1,232 +0,0 @@
|
|||
package morph
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/config"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/innerring"
|
||||
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
|
||||
"github.com/nspcc-dev/neo-go/pkg/encoding/address"
|
||||
"github.com/nspcc-dev/neo-go/pkg/encoding/fixedn"
|
||||
"github.com/nspcc-dev/neo-go/pkg/io"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/gas"
|
||||
"github.com/nspcc-dev/neo-go/pkg/smartcontract"
|
||||
"github.com/nspcc-dev/neo-go/pkg/smartcontract/callflag"
|
||||
"github.com/nspcc-dev/neo-go/pkg/util"
|
||||
"github.com/nspcc-dev/neo-go/pkg/vm/emit"
|
||||
"github.com/nspcc-dev/neo-go/pkg/vm/opcode"
|
||||
"github.com/nspcc-dev/neo-go/pkg/wallet"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
"golang.org/x/sync/errgroup"
|
||||
)
|
||||
|
||||
const (
|
||||
singleAccountName = "single"
|
||||
committeeAccountName = "committee"
|
||||
consensusAccountName = "consensus"
|
||||
)
|
||||
|
||||
func generateAlphabetCreds(cmd *cobra.Command, _ []string) error {
|
||||
// alphabet size is not part of the config
|
||||
size, err := cmd.Flags().GetUint(alphabetSizeFlag)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if size == 0 {
|
||||
return errors.New("size must be > 0")
|
||||
}
|
||||
if size > maxAlphabetNodes {
|
||||
return ErrTooManyAlphabetNodes
|
||||
}
|
||||
|
||||
v := viper.GetViper()
|
||||
walletDir := config.ResolveHomePath(viper.GetString(alphabetWalletsFlag))
|
||||
pwds, err := initializeWallets(v, walletDir, int(size))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = initializeContractWallet(v, walletDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cmd.Println("size:", size)
|
||||
cmd.Println("alphabet-wallets:", walletDir)
|
||||
for i := range pwds {
|
||||
cmd.Printf("wallet[%d]: %s\n", i, pwds[i])
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func initializeWallets(v *viper.Viper, walletDir string, size int) ([]string, error) {
|
||||
wallets := make([]*wallet.Wallet, size)
|
||||
pubs := make(keys.PublicKeys, size)
|
||||
passwords := make([]string, size)
|
||||
|
||||
for i := range wallets {
|
||||
password, err := config.GetPassword(v, innerring.GlagoliticLetter(i).String())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't fetch password: %w", err)
|
||||
}
|
||||
|
||||
p := filepath.Join(walletDir, innerring.GlagoliticLetter(i).String()+".json")
|
||||
f, err := os.OpenFile(p, os.O_CREATE, 0o644)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't create wallet file: %w", err)
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
return nil, fmt.Errorf("can't close wallet file: %w", err)
|
||||
}
|
||||
w, err := wallet.NewWallet(p)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't create wallet: %w", err)
|
||||
}
|
||||
if err := w.CreateAccount(singleAccountName, password); err != nil {
|
||||
return nil, fmt.Errorf("can't create account: %w", err)
|
||||
}
|
||||
|
||||
passwords[i] = password
|
||||
wallets[i] = w
|
||||
pubs[i] = w.Accounts[0].PrivateKey().PublicKey()
|
||||
}
|
||||
|
||||
var errG errgroup.Group
|
||||
|
||||
// Create committee account with N/2+1 multi-signature.
|
||||
majCount := smartcontract.GetMajorityHonestNodeCount(size)
|
||||
// Create consensus account with 2*N/3+1 multi-signature.
|
||||
bftCount := smartcontract.GetDefaultHonestNodeCount(size)
|
||||
for i := range wallets {
|
||||
i := i
|
||||
ps := pubs.Copy()
|
||||
errG.Go(func() error {
|
||||
if err := addMultisigAccount(wallets[i], majCount, committeeAccountName, passwords[i], ps); err != nil {
|
||||
return fmt.Errorf("can't create committee account: %w", err)
|
||||
}
|
||||
if err := addMultisigAccount(wallets[i], bftCount, consensusAccountName, passwords[i], ps); err != nil {
|
||||
return fmt.Errorf("can't create consentus account: %w", err)
|
||||
}
|
||||
if err := wallets[i].SavePretty(); err != nil {
|
||||
return fmt.Errorf("can't save wallet: %w", err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
if err := errG.Wait(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return passwords, nil
|
||||
}
|
||||
|
||||
func addMultisigAccount(w *wallet.Wallet, m int, name, password string, pubs keys.PublicKeys) error {
|
||||
acc := wallet.NewAccountFromPrivateKey(w.Accounts[0].PrivateKey())
|
||||
acc.Label = name
|
||||
|
||||
if err := acc.ConvertMultisig(m, pubs); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := acc.Encrypt(password, keys.NEP2ScryptParams()); err != nil {
|
||||
return err
|
||||
}
|
||||
w.AddAccount(acc)
|
||||
return nil
|
||||
}
|
||||
|
||||
func generateStorageCreds(cmd *cobra.Command, _ []string) error {
|
||||
return refillGas(cmd, storageGasConfigFlag, true)
|
||||
}
|
||||
|
||||
func refillGas(cmd *cobra.Command, gasFlag string, createWallet bool) (err error) {
|
||||
// storage wallet path is not part of the config
|
||||
storageWalletPath, _ := cmd.Flags().GetString(storageWalletFlag)
|
||||
// wallet address is not part of the config
|
||||
walletAddress, _ := cmd.Flags().GetString(walletAddressFlag)
|
||||
|
||||
var gasReceiver util.Uint160
|
||||
|
||||
if len(walletAddress) != 0 {
|
||||
gasReceiver, err = address.StringToUint160(walletAddress)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid wallet address %s: %w", walletAddress, err)
|
||||
}
|
||||
} else {
|
||||
if storageWalletPath == "" {
|
||||
return fmt.Errorf("missing wallet path (use '--%s <out.json>')", storageWalletFlag)
|
||||
}
|
||||
|
||||
var w *wallet.Wallet
|
||||
|
||||
if createWallet {
|
||||
w, err = wallet.NewWallet(storageWalletPath)
|
||||
} else {
|
||||
w, err = wallet.NewWalletFromFile(storageWalletPath)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't create wallet: %w", err)
|
||||
}
|
||||
|
||||
if createWallet {
|
||||
var password string
|
||||
|
||||
label, _ := cmd.Flags().GetString(storageWalletLabelFlag)
|
||||
password, err := config.GetStoragePassword(viper.GetViper(), label)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't fetch password: %w", err)
|
||||
}
|
||||
|
||||
if label == "" {
|
||||
label = singleAccountName
|
||||
}
|
||||
|
||||
if err := w.CreateAccount(label, password); err != nil {
|
||||
return fmt.Errorf("can't create account: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
gasReceiver = w.Accounts[0].Contract.ScriptHash()
|
||||
}
|
||||
|
||||
gasStr := viper.GetString(gasFlag)
|
||||
|
||||
gasAmount, err := parseGASAmount(gasStr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
wCtx, err := newInitializeContext(cmd, viper.GetViper())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
bw := io.NewBufBinWriter()
|
||||
emit.AppCall(bw.BinWriter, gas.Hash, "transfer", callflag.All,
|
||||
wCtx.CommitteeAcc.Contract.ScriptHash(), gasReceiver, int64(gasAmount), nil)
|
||||
emit.Opcodes(bw.BinWriter, opcode.ASSERT)
|
||||
if bw.Err != nil {
|
||||
return fmt.Errorf("BUG: invalid transfer arguments: %w", bw.Err)
|
||||
}
|
||||
|
||||
if err := wCtx.sendCommitteeTx(bw.Bytes(), false); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return wCtx.awaitTx()
|
||||
}
|
||||
|
||||
func parseGASAmount(s string) (fixedn.Fixed8, error) {
|
||||
gasAmount, err := fixedn.Fixed8FromString(s)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("invalid GAS amount %s: %w", s, err)
|
||||
}
|
||||
if gasAmount <= 0 {
|
||||
return 0, fmt.Errorf("GAS amount must be positive (got %d)", gasAmount)
|
||||
}
|
||||
return gasAmount, nil
|
||||
}
|
193
cmd/frostfs-adm/internal/modules/morph/generate/generate.go
Normal file
193
cmd/frostfs-adm/internal/modules/morph/generate/generate.go
Normal file
|
@ -0,0 +1,193 @@
|
|||
package generate
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/config"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/constants"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/helper"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/innerring"
|
||||
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
|
||||
"github.com/nspcc-dev/neo-go/pkg/io"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/gas"
|
||||
"github.com/nspcc-dev/neo-go/pkg/smartcontract"
|
||||
"github.com/nspcc-dev/neo-go/pkg/smartcontract/callflag"
|
||||
"github.com/nspcc-dev/neo-go/pkg/util"
|
||||
"github.com/nspcc-dev/neo-go/pkg/vm/emit"
|
||||
"github.com/nspcc-dev/neo-go/pkg/vm/opcode"
|
||||
"github.com/nspcc-dev/neo-go/pkg/wallet"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
"golang.org/x/sync/errgroup"
|
||||
)
|
||||
|
||||
func AlphabetCreds(cmd *cobra.Command, _ []string) error {
|
||||
// alphabet size is not part of the config
|
||||
size, err := cmd.Flags().GetUint(commonflags.AlphabetSizeFlag)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if size == 0 {
|
||||
return errors.New("size must be > 0")
|
||||
}
|
||||
if size > constants.MaxAlphabetNodes {
|
||||
return helper.ErrTooManyAlphabetNodes
|
||||
}
|
||||
|
||||
v := viper.GetViper()
|
||||
walletDir := config.ResolveHomePath(viper.GetString(commonflags.AlphabetWalletsFlag))
|
||||
pwds, err := initializeWallets(v, walletDir, int(size))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = helper.InitializeContractWallet(v, walletDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cmd.Println("size:", size)
|
||||
cmd.Println("alphabet-wallets:", walletDir)
|
||||
for i := range pwds {
|
||||
cmd.Printf("wallet[%d]: %s\n", i, pwds[i])
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func initializeWallets(v *viper.Viper, walletDir string, size int) ([]string, error) {
|
||||
wallets := make([]*wallet.Wallet, size)
|
||||
pubs := make(keys.PublicKeys, size)
|
||||
passwords := make([]string, size)
|
||||
|
||||
var errG errgroup.Group
|
||||
|
||||
for i := range wallets {
|
||||
password, err := config.GetPassword(v, innerring.GlagoliticLetter(i).String())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't fetch password: %w", err)
|
||||
}
|
||||
|
||||
errG.Go(func() error {
|
||||
p := filepath.Join(walletDir, innerring.GlagoliticLetter(i).String()+".json")
|
||||
f, err := os.OpenFile(p, os.O_CREATE, 0o644)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't create wallet file: %w", err)
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
return fmt.Errorf("can't close wallet file: %w", err)
|
||||
}
|
||||
w, err := wallet.NewWallet(p)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't create wallet: %w", err)
|
||||
}
|
||||
if err := w.CreateAccount(constants.SingleAccountName, password); err != nil {
|
||||
return fmt.Errorf("can't create account: %w", err)
|
||||
}
|
||||
|
||||
passwords[i] = password
|
||||
wallets[i] = w
|
||||
pubs[i] = w.Accounts[0].PrivateKey().PublicKey()
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
if err := errG.Wait(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Create committee account with N/2+1 multi-signature.
|
||||
majCount := smartcontract.GetMajorityHonestNodeCount(size)
|
||||
// Create consensus account with 2*N/3+1 multi-signature.
|
||||
bftCount := smartcontract.GetDefaultHonestNodeCount(size)
|
||||
for i := range wallets {
|
||||
ps := pubs.Copy()
|
||||
errG.Go(func() error {
|
||||
if err := addMultisigAccount(wallets[i], majCount, constants.CommitteeAccountName, passwords[i], ps); err != nil {
|
||||
return fmt.Errorf("can't create committee account: %w", err)
|
||||
}
|
||||
if err := addMultisigAccount(wallets[i], bftCount, constants.ConsensusAccountName, passwords[i], ps); err != nil {
|
||||
return fmt.Errorf("can't create consentus account: %w", err)
|
||||
}
|
||||
if err := wallets[i].SavePretty(); err != nil {
|
||||
return fmt.Errorf("can't save wallet: %w", err)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
if err := errG.Wait(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return passwords, nil
|
||||
}
|
||||
|
||||
func addMultisigAccount(w *wallet.Wallet, m int, name, password string, pubs keys.PublicKeys) error {
|
||||
acc := wallet.NewAccountFromPrivateKey(w.Accounts[0].PrivateKey())
|
||||
acc.Label = name
|
||||
|
||||
if err := acc.ConvertMultisig(m, pubs); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := acc.Encrypt(password, keys.NEP2ScryptParams()); err != nil {
|
||||
return err
|
||||
}
|
||||
w.AddAccount(acc)
|
||||
return nil
|
||||
}
|
||||
|
||||
func generateStorageCreds(cmd *cobra.Command, _ []string) error {
|
||||
walletPath, _ := cmd.Flags().GetString(commonflags.StorageWalletFlag)
|
||||
w, err := wallet.NewWallet(walletPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create wallet: %w", err)
|
||||
}
|
||||
|
||||
label, _ := cmd.Flags().GetString(storageWalletLabelFlag)
|
||||
password, err := config.GetStoragePassword(viper.GetViper(), label)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't fetch password: %w", err)
|
||||
}
|
||||
|
||||
if label == "" {
|
||||
label = constants.SingleAccountName
|
||||
}
|
||||
|
||||
if err := w.CreateAccount(label, password); err != nil {
|
||||
return fmt.Errorf("can't create account: %w", err)
|
||||
}
|
||||
return refillGas(cmd, storageGasConfigFlag, w.Accounts[0].ScriptHash())
|
||||
}
|
||||
|
||||
func refillGas(cmd *cobra.Command, gasFlag string, gasReceivers ...util.Uint160) (err error) {
|
||||
gasStr := viper.GetString(gasFlag)
|
||||
|
||||
gasAmount, err := helper.ParseGASAmount(gasStr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
wCtx, err := helper.NewInitializeContext(cmd, viper.GetViper())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
bw := io.NewBufBinWriter()
|
||||
for _, gasReceiver := range gasReceivers {
|
||||
emit.AppCall(bw.BinWriter, gas.Hash, "transfer", callflag.All,
|
||||
wCtx.CommitteeAcc.Contract.ScriptHash(), gasReceiver, int64(gasAmount), nil)
|
||||
emit.Opcodes(bw.BinWriter, opcode.ASSERT)
|
||||
}
|
||||
if bw.Err != nil {
|
||||
return fmt.Errorf("BUG: invalid transfer arguments: %w", bw.Err)
|
||||
}
|
||||
|
||||
if err := wCtx.SendCommitteeTx(bw.Bytes(), false); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return wCtx.AwaitTx()
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package morph
|
||||
package generate
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
|
@ -10,6 +10,8 @@ import (
|
|||
"sync"
|
||||
"testing"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/constants"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/innerring"
|
||||
"github.com/nspcc-dev/neo-go/cli/input"
|
||||
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
|
||||
|
@ -20,57 +22,53 @@ import (
|
|||
"golang.org/x/term"
|
||||
)
|
||||
|
||||
const testContractPassword = "grouppass"
|
||||
|
||||
func TestGenerateAlphabet(t *testing.T) {
|
||||
const size = 4
|
||||
|
||||
walletDir := t.TempDir()
|
||||
buf := setupTestTerminal(t)
|
||||
|
||||
cmd := generateAlphabetCmd
|
||||
cmd := GenerateAlphabetCmd
|
||||
v := viper.GetViper()
|
||||
|
||||
t.Run("zero size", func(t *testing.T) {
|
||||
buf.Reset()
|
||||
v.Set(alphabetWalletsFlag, walletDir)
|
||||
require.NoError(t, cmd.Flags().Set(alphabetSizeFlag, "0"))
|
||||
v.Set(commonflags.AlphabetWalletsFlag, walletDir)
|
||||
require.NoError(t, cmd.Flags().Set(commonflags.AlphabetSizeFlag, "0"))
|
||||
buf.WriteString("pass\r")
|
||||
require.Error(t, generateAlphabetCreds(cmd, nil))
|
||||
require.Error(t, AlphabetCreds(cmd, nil))
|
||||
})
|
||||
t.Run("no password provided", func(t *testing.T) {
|
||||
buf.Reset()
|
||||
v.Set(alphabetWalletsFlag, walletDir)
|
||||
require.NoError(t, cmd.Flags().Set(alphabetSizeFlag, "1"))
|
||||
require.Error(t, generateAlphabetCreds(cmd, nil))
|
||||
v.Set(commonflags.AlphabetWalletsFlag, walletDir)
|
||||
require.NoError(t, cmd.Flags().Set(commonflags.AlphabetSizeFlag, "1"))
|
||||
require.Error(t, AlphabetCreds(cmd, nil))
|
||||
})
|
||||
t.Run("missing directory", func(t *testing.T) {
|
||||
buf.Reset()
|
||||
dir := filepath.Join(os.TempDir(), "notexist."+strconv.FormatUint(rand.Uint64(), 10))
|
||||
v.Set(alphabetWalletsFlag, dir)
|
||||
require.NoError(t, cmd.Flags().Set(alphabetSizeFlag, "1"))
|
||||
v.Set(commonflags.AlphabetWalletsFlag, dir)
|
||||
require.NoError(t, cmd.Flags().Set(commonflags.AlphabetSizeFlag, "1"))
|
||||
buf.WriteString("pass\r")
|
||||
require.Error(t, generateAlphabetCreds(cmd, nil))
|
||||
require.Error(t, AlphabetCreds(cmd, nil))
|
||||
})
|
||||
t.Run("no password for contract group wallet", func(t *testing.T) {
|
||||
buf.Reset()
|
||||
v.Set(alphabetWalletsFlag, walletDir)
|
||||
require.NoError(t, cmd.Flags().Set(alphabetSizeFlag, strconv.FormatUint(size, 10)))
|
||||
for i := uint64(0); i < size; i++ {
|
||||
buf.WriteString(strconv.FormatUint(i, 10) + "\r")
|
||||
}
|
||||
require.Error(t, generateAlphabetCreds(cmd, nil))
|
||||
v.Set(commonflags.AlphabetWalletsFlag, walletDir)
|
||||
require.NoError(t, cmd.Flags().Set(commonflags.AlphabetSizeFlag, "1"))
|
||||
buf.WriteString("pass\r")
|
||||
require.Error(t, AlphabetCreds(cmd, nil))
|
||||
})
|
||||
|
||||
const size = 4
|
||||
|
||||
buf.Reset()
|
||||
v.Set(alphabetWalletsFlag, walletDir)
|
||||
require.NoError(t, generateAlphabetCmd.Flags().Set(alphabetSizeFlag, strconv.FormatUint(size, 10)))
|
||||
for i := uint64(0); i < size; i++ {
|
||||
v.Set(commonflags.AlphabetWalletsFlag, walletDir)
|
||||
require.NoError(t, GenerateAlphabetCmd.Flags().Set(commonflags.AlphabetSizeFlag, strconv.FormatUint(size, 10)))
|
||||
for i := range uint64(size) {
|
||||
buf.WriteString(strconv.FormatUint(i, 10) + "\r")
|
||||
}
|
||||
|
||||
buf.WriteString(testContractPassword + "\r")
|
||||
require.NoError(t, generateAlphabetCreds(generateAlphabetCmd, nil))
|
||||
buf.WriteString(constants.TestContractPassword + "\r")
|
||||
require.NoError(t, AlphabetCreds(GenerateAlphabetCmd, nil))
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for i := uint64(0); i < size; i++ {
|
||||
|
@ -87,12 +85,12 @@ func TestGenerateAlphabet(t *testing.T) {
|
|||
err := a.Decrypt(strconv.FormatUint(i, 10), keys.NEP2ScryptParams())
|
||||
require.NoError(t, err, "can't decrypt account")
|
||||
switch a.Label {
|
||||
case consensusAccountName:
|
||||
case constants.ConsensusAccountName:
|
||||
require.Equal(t, smartcontract.GetDefaultHonestNodeCount(size), len(a.Contract.Parameters))
|
||||
case committeeAccountName:
|
||||
case constants.CommitteeAccountName:
|
||||
require.Equal(t, smartcontract.GetMajorityHonestNodeCount(size), len(a.Contract.Parameters))
|
||||
default:
|
||||
require.Equal(t, singleAccountName, a.Label)
|
||||
require.Equal(t, constants.SingleAccountName, a.Label)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
@ -100,11 +98,11 @@ func TestGenerateAlphabet(t *testing.T) {
|
|||
wg.Wait()
|
||||
|
||||
t.Run("check contract group wallet", func(t *testing.T) {
|
||||
p := filepath.Join(walletDir, contractWalletFilename)
|
||||
p := filepath.Join(walletDir, constants.ContractWalletFilename)
|
||||
w, err := wallet.NewWalletFromFile(p)
|
||||
require.NoError(t, err, "contract wallet doesn't exist")
|
||||
require.Equal(t, 1, len(w.Accounts), "contract wallet must have 1 accout")
|
||||
require.NoError(t, w.Accounts[0].Decrypt(testContractPassword, keys.NEP2ScryptParams()))
|
||||
require.NoError(t, w.Accounts[0].Decrypt(constants.TestContractPassword, keys.NEP2ScryptParams()))
|
||||
})
|
||||
}
|
||||
|
101
cmd/frostfs-adm/internal/modules/morph/generate/root.go
Normal file
101
cmd/frostfs-adm/internal/modules/morph/generate/root.go
Normal file
|
@ -0,0 +1,101 @@
|
|||
package generate
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
"github.com/nspcc-dev/neo-go/pkg/encoding/address"
|
||||
"github.com/nspcc-dev/neo-go/pkg/util"
|
||||
"github.com/nspcc-dev/neo-go/pkg/wallet"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
const (
|
||||
storageWalletLabelFlag = "label"
|
||||
storageGasCLIFlag = "initial-gas"
|
||||
storageGasConfigFlag = "storage.initial_gas"
|
||||
walletAddressFlag = "wallet-address"
|
||||
)
|
||||
|
||||
var (
|
||||
GenerateStorageCmd = &cobra.Command{
|
||||
Use: "generate-storage-wallet",
|
||||
Short: "Generate storage node wallet for the morph network",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.AlphabetWalletsFlag, cmd.Flags().Lookup(commonflags.AlphabetWalletsFlag))
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
_ = viper.BindPFlag(storageGasConfigFlag, cmd.Flags().Lookup(storageGasCLIFlag))
|
||||
},
|
||||
RunE: generateStorageCreds,
|
||||
}
|
||||
RefillGasCmd = &cobra.Command{
|
||||
Use: "refill-gas",
|
||||
Short: "Refill GAS of storage node's wallet in the morph network",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.AlphabetWalletsFlag, cmd.Flags().Lookup(commonflags.AlphabetWalletsFlag))
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
_ = viper.BindPFlag(commonflags.RefillGasAmountFlag, cmd.Flags().Lookup(commonflags.RefillGasAmountFlag))
|
||||
},
|
||||
RunE: func(cmd *cobra.Command, _ []string) error {
|
||||
storageWalletPaths, _ := cmd.Flags().GetStringArray(commonflags.StorageWalletFlag)
|
||||
walletAddresses, _ := cmd.Flags().GetStringArray(walletAddressFlag)
|
||||
|
||||
var gasReceivers []util.Uint160
|
||||
for _, walletAddress := range walletAddresses {
|
||||
addr, err := address.StringToUint160(walletAddress)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid wallet address %s: %w", walletAddress, err)
|
||||
}
|
||||
|
||||
gasReceivers = append(gasReceivers, addr)
|
||||
}
|
||||
for _, storageWalletPath := range storageWalletPaths {
|
||||
w, err := wallet.NewWalletFromFile(storageWalletPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't create wallet: %w", err)
|
||||
}
|
||||
|
||||
gasReceivers = append(gasReceivers, w.Accounts[0].Contract.ScriptHash())
|
||||
}
|
||||
return refillGas(cmd, commonflags.RefillGasAmountFlag, gasReceivers...)
|
||||
},
|
||||
}
|
||||
GenerateAlphabetCmd = &cobra.Command{
|
||||
Use: "generate-alphabet",
|
||||
Short: "Generate alphabet wallets for consensus nodes of the morph network",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
// PreRun fixes https://github.com/spf13/viper/issues/233
|
||||
_ = viper.BindPFlag(commonflags.AlphabetWalletsFlag, cmd.Flags().Lookup(commonflags.AlphabetWalletsFlag))
|
||||
},
|
||||
RunE: AlphabetCreds,
|
||||
}
|
||||
)
|
||||
|
||||
func initRefillGasCmd() {
|
||||
RefillGasCmd.Flags().String(commonflags.AlphabetWalletsFlag, "", commonflags.AlphabetWalletsFlagDesc)
|
||||
RefillGasCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
RefillGasCmd.Flags().StringArray(commonflags.StorageWalletFlag, nil, "Path to storage node wallet")
|
||||
RefillGasCmd.Flags().StringArray(walletAddressFlag, nil, "Address of wallet")
|
||||
RefillGasCmd.Flags().String(commonflags.RefillGasAmountFlag, "", "Additional amount of GAS to transfer")
|
||||
RefillGasCmd.MarkFlagsOneRequired(walletAddressFlag, commonflags.StorageWalletFlag)
|
||||
}
|
||||
|
||||
func initGenerateStorageCmd() {
|
||||
GenerateStorageCmd.Flags().String(commonflags.AlphabetWalletsFlag, "", commonflags.AlphabetWalletsFlagDesc)
|
||||
GenerateStorageCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
GenerateStorageCmd.Flags().String(commonflags.StorageWalletFlag, "", "Path to new storage node wallet")
|
||||
GenerateStorageCmd.Flags().String(storageGasCLIFlag, "", "Initial amount of GAS to transfer")
|
||||
GenerateStorageCmd.Flags().StringP(storageWalletLabelFlag, "l", "", "Wallet label")
|
||||
}
|
||||
|
||||
func initGenerateAlphabetCmd() {
|
||||
GenerateAlphabetCmd.Flags().String(commonflags.AlphabetWalletsFlag, "", commonflags.AlphabetWalletsFlagDesc)
|
||||
GenerateAlphabetCmd.Flags().Uint(commonflags.AlphabetSizeFlag, 7, "Amount of alphabet wallets to generate")
|
||||
}
|
||||
|
||||
func init() {
|
||||
initRefillGasCmd()
|
||||
initGenerateStorageCmd()
|
||||
initGenerateAlphabetCmd()
|
||||
}
|
|
@ -1,106 +0,0 @@
|
|||
package morph
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/config"
|
||||
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
|
||||
"github.com/nspcc-dev/neo-go/pkg/smartcontract/manifest"
|
||||
"github.com/nspcc-dev/neo-go/pkg/util"
|
||||
"github.com/nspcc-dev/neo-go/pkg/wallet"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
const (
|
||||
contractWalletFilename = "contract.json"
|
||||
contractWalletPasswordKey = "contract"
|
||||
)
|
||||
|
||||
func initializeContractWallet(v *viper.Viper, walletDir string) (*wallet.Wallet, error) {
|
||||
password, err := config.GetPassword(v, contractWalletPasswordKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
w, err := wallet.NewWallet(filepath.Join(walletDir, contractWalletFilename))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
acc, err := wallet.NewAccount()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = acc.Encrypt(password, keys.NEP2ScryptParams())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
w.AddAccount(acc)
|
||||
if err := w.SavePretty(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return w, nil
|
||||
}
|
||||
|
||||
func openContractWallet(v *viper.Viper, cmd *cobra.Command, walletDir string) (*wallet.Wallet, error) {
|
||||
p := filepath.Join(walletDir, contractWalletFilename)
|
||||
w, err := wallet.NewWalletFromFile(p)
|
||||
if err != nil {
|
||||
if !os.IsNotExist(err) {
|
||||
return nil, fmt.Errorf("can't open wallet: %w", err)
|
||||
}
|
||||
|
||||
cmd.Printf("Contract group wallet is missing, initialize at %s\n", p)
|
||||
return initializeContractWallet(v, walletDir)
|
||||
}
|
||||
|
||||
password, err := config.GetPassword(v, contractWalletPasswordKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for i := range w.Accounts {
|
||||
if err := w.Accounts[i].Decrypt(password, keys.NEP2ScryptParams()); err != nil {
|
||||
return nil, fmt.Errorf("can't unlock wallet: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return w, nil
|
||||
}
|
||||
|
||||
func (c *initializeContext) addManifestGroup(h util.Uint160, cs *contractState) error {
|
||||
priv := c.ContractWallet.Accounts[0].PrivateKey()
|
||||
pub := priv.PublicKey()
|
||||
|
||||
sig := priv.Sign(h.BytesBE())
|
||||
found := false
|
||||
|
||||
for i := range cs.Manifest.Groups {
|
||||
if cs.Manifest.Groups[i].PublicKey.Equal(pub) {
|
||||
cs.Manifest.Groups[i].Signature = sig
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
cs.Manifest.Groups = append(cs.Manifest.Groups, manifest.Group{
|
||||
PublicKey: pub,
|
||||
Signature: sig,
|
||||
})
|
||||
}
|
||||
|
||||
data, err := json.Marshal(cs.Manifest)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cs.RawManifest = data
|
||||
return nil
|
||||
}
|
164
cmd/frostfs-adm/internal/modules/morph/helper/actor.go
Normal file
164
cmd/frostfs-adm/internal/modules/morph/helper/actor.go
Normal file
|
@ -0,0 +1,164 @@
|
|||
package helper
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/config"
|
||||
commonCmd "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/internal/common"
|
||||
"github.com/google/uuid"
|
||||
"github.com/nspcc-dev/neo-go/pkg/core/state"
|
||||
"github.com/nspcc-dev/neo-go/pkg/core/transaction"
|
||||
"github.com/nspcc-dev/neo-go/pkg/neorpc/result"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/actor"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/invoker"
|
||||
"github.com/nspcc-dev/neo-go/pkg/smartcontract/context"
|
||||
"github.com/nspcc-dev/neo-go/pkg/util"
|
||||
"github.com/nspcc-dev/neo-go/pkg/vm/stackitem"
|
||||
"github.com/nspcc-dev/neo-go/pkg/wallet"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
// LocalActor is a kludge, do not use it outside of the morph commands.
|
||||
type LocalActor struct {
|
||||
neoActor *actor.Actor
|
||||
accounts []*wallet.Account
|
||||
Invoker *invoker.Invoker
|
||||
rpcInvoker invoker.RPCInvoke
|
||||
}
|
||||
|
||||
// NewLocalActor create LocalActor with accounts form provided wallets.
|
||||
// In case of empty wallets provided created actor with dummy account only for read operation.
|
||||
//
|
||||
// If wallets are provided, the contract client will use accounts with accName name from these wallets.
|
||||
// To determine which account name should be used in a contract client, refer to how the contract
|
||||
// verifies the transaction signature.
|
||||
func NewLocalActor(cmd *cobra.Command, c actor.RPCActor, accName string) (*LocalActor, error) {
|
||||
walletDir := config.ResolveHomePath(viper.GetString(commonflags.AlphabetWalletsFlag))
|
||||
var act *actor.Actor
|
||||
var accounts []*wallet.Account
|
||||
|
||||
wallets, err := GetAlphabetWallets(viper.GetViper(), walletDir)
|
||||
commonCmd.ExitOnErr(cmd, "unable to get alphabet wallets: %w", err)
|
||||
|
||||
for _, w := range wallets {
|
||||
acc, err := GetWalletAccount(w, accName)
|
||||
commonCmd.ExitOnErr(cmd, fmt.Sprintf("can't find %s account: %%w", accName), err)
|
||||
accounts = append(accounts, acc)
|
||||
}
|
||||
act, err = actor.New(c, []actor.SignerAccount{{
|
||||
Signer: transaction.Signer{
|
||||
Account: accounts[0].Contract.ScriptHash(),
|
||||
Scopes: transaction.Global,
|
||||
},
|
||||
Account: accounts[0],
|
||||
}})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &LocalActor{
|
||||
neoActor: act,
|
||||
accounts: accounts,
|
||||
Invoker: &act.Invoker,
|
||||
rpcInvoker: c,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (a *LocalActor) SendCall(contract util.Uint160, method string, params ...any) (util.Uint256, uint32, error) {
|
||||
tx, err := a.neoActor.MakeCall(contract, method, params...)
|
||||
if err != nil {
|
||||
return util.Uint256{}, 0, err
|
||||
}
|
||||
err = a.resign(tx)
|
||||
if err != nil {
|
||||
return util.Uint256{}, 0, err
|
||||
}
|
||||
return a.neoActor.Send(tx)
|
||||
}
|
||||
|
||||
func (a *LocalActor) SendRun(script []byte) (util.Uint256, uint32, error) {
|
||||
tx, err := a.neoActor.MakeRun(script)
|
||||
if err != nil {
|
||||
return util.Uint256{}, 0, err
|
||||
}
|
||||
err = a.resign(tx)
|
||||
if err != nil {
|
||||
return util.Uint256{}, 0, err
|
||||
}
|
||||
return a.neoActor.Send(tx)
|
||||
}
|
||||
|
||||
// resign is used to sign tx with committee accounts.
|
||||
// Inside the methods `MakeCall` and `SendRun` of the NeoGO's actor transaction is signing by committee account,
|
||||
// because actor uses committee wallet.
|
||||
// But it is not enough, need to sign with another committee accounts.
|
||||
func (a *LocalActor) resign(tx *transaction.Transaction) error {
|
||||
if len(a.accounts[0].Contract.Parameters) > 1 {
|
||||
// Use parameter context to avoid dealing with signature order.
|
||||
network := a.neoActor.GetNetwork()
|
||||
pc := context.NewParameterContext("", network, tx)
|
||||
h := a.accounts[0].Contract.ScriptHash()
|
||||
for _, acc := range a.accounts {
|
||||
priv := acc.PrivateKey()
|
||||
sign := priv.SignHashable(uint32(network), tx)
|
||||
if err := pc.AddSignature(h, acc.Contract, priv.PublicKey(), sign); err != nil {
|
||||
return fmt.Errorf("can't add signature: %w", err)
|
||||
}
|
||||
if len(pc.Items[h].Signatures) == len(acc.Contract.Parameters) {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
w, err := pc.GetWitness(h)
|
||||
if err != nil {
|
||||
return fmt.Errorf("incomplete signature: %w", err)
|
||||
}
|
||||
tx.Scripts[0] = *w
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *LocalActor) Wait(h util.Uint256, vub uint32, err error) (*state.AppExecResult, error) {
|
||||
return a.neoActor.Wait(h, vub, err)
|
||||
}
|
||||
|
||||
func (a *LocalActor) Sender() util.Uint160 {
|
||||
return a.neoActor.Sender()
|
||||
}
|
||||
|
||||
func (a *LocalActor) Call(contract util.Uint160, operation string, params ...any) (*result.Invoke, error) {
|
||||
return a.neoActor.Call(contract, operation, params...)
|
||||
}
|
||||
|
||||
func (a *LocalActor) CallAndExpandIterator(_ util.Uint160, _ string, _ int, _ ...any) (*result.Invoke, error) {
|
||||
panic("unimplemented")
|
||||
}
|
||||
|
||||
func (a *LocalActor) TerminateSession(_ uuid.UUID) error {
|
||||
panic("unimplemented")
|
||||
}
|
||||
|
||||
func (a *LocalActor) TraverseIterator(sessionID uuid.UUID, iterator *result.Iterator, num int) ([]stackitem.Item, error) {
|
||||
return a.neoActor.TraverseIterator(sessionID, iterator, num)
|
||||
}
|
||||
|
||||
func (a *LocalActor) MakeRun(_ []byte) (*transaction.Transaction, error) {
|
||||
panic("unimplemented")
|
||||
}
|
||||
|
||||
func (a *LocalActor) MakeUnsignedCall(_ util.Uint160, _ string, _ []transaction.Attribute, _ ...any) (*transaction.Transaction, error) {
|
||||
panic("unimplemented")
|
||||
}
|
||||
|
||||
func (a *LocalActor) MakeUnsignedRun(_ []byte, _ []transaction.Attribute) (*transaction.Transaction, error) {
|
||||
panic("unimplemented")
|
||||
}
|
||||
|
||||
func (a *LocalActor) MakeCall(_ util.Uint160, _ string, _ ...any) (*transaction.Transaction, error) {
|
||||
panic("unimplemented")
|
||||
}
|
||||
|
||||
func (a *LocalActor) GetRPCInvoker() invoker.RPCInvoke {
|
||||
return a.rpcInvoker
|
||||
}
|
171
cmd/frostfs-adm/internal/modules/morph/helper/contract.go
Normal file
171
cmd/frostfs-adm/internal/modules/morph/helper/contract.go
Normal file
|
@ -0,0 +1,171 @@
|
|||
package helper
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/constants"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/invoker"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/management"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/unwrap"
|
||||
"github.com/nspcc-dev/neo-go/pkg/smartcontract"
|
||||
"github.com/nspcc-dev/neo-go/pkg/util"
|
||||
"github.com/nspcc-dev/neo-go/pkg/vm/stackitem"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
func getFrostfsIDAdminFromContract(roInvoker *invoker.Invoker) (util.Uint160, bool, error) {
|
||||
r := management.NewReader(roInvoker)
|
||||
cs, err := GetContractByID(r, 1)
|
||||
if err != nil {
|
||||
return util.Uint160{}, false, fmt.Errorf("get nns contract: %w", err)
|
||||
}
|
||||
fidHash, err := NNSResolveHash(roInvoker, cs.Hash, DomainOf(constants.FrostfsIDContract))
|
||||
if err != nil {
|
||||
return util.Uint160{}, false, fmt.Errorf("resolve frostfsid contract hash: %w", err)
|
||||
}
|
||||
item, err := unwrap.Item(roInvoker.Call(fidHash, "getAdmin"))
|
||||
if err != nil {
|
||||
return util.Uint160{}, false, fmt.Errorf("getAdmin: %w", err)
|
||||
}
|
||||
if _, ok := item.(stackitem.Null); ok {
|
||||
return util.Uint160{}, false, nil
|
||||
}
|
||||
|
||||
bs, err := item.TryBytes()
|
||||
if err != nil {
|
||||
return util.Uint160{}, true, fmt.Errorf("getAdmin: decode result: %w", err)
|
||||
}
|
||||
h, err := util.Uint160DecodeBytesBE(bs)
|
||||
if err != nil {
|
||||
return util.Uint160{}, true, fmt.Errorf("getAdmin: decode result: %w", err)
|
||||
}
|
||||
return h, true, nil
|
||||
}
|
||||
|
||||
func GetContractDeployData(c *InitializeContext, ctrName string, keysParam []any, method string) ([]any, error) {
|
||||
items := make([]any, 0, 6)
|
||||
|
||||
switch ctrName {
|
||||
case constants.FrostfsContract:
|
||||
items = append(items,
|
||||
c.Contracts[constants.ProcessingContract].Hash,
|
||||
keysParam,
|
||||
smartcontract.Parameter{})
|
||||
case constants.ProcessingContract:
|
||||
items = append(items, c.Contracts[constants.FrostfsContract].Hash)
|
||||
return items[1:], nil // no notary info
|
||||
case constants.BalanceContract:
|
||||
items = append(items,
|
||||
c.Contracts[constants.NetmapContract].Hash,
|
||||
c.Contracts[constants.ContainerContract].Hash)
|
||||
case constants.ContainerContract:
|
||||
// In case if NNS is updated multiple times, we can't calculate
|
||||
// it's actual hash based on local data, thus query chain.
|
||||
r := management.NewReader(c.ReadOnlyInvoker)
|
||||
nnsCs, err := GetContractByID(r, 1)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get nns contract: %w", err)
|
||||
}
|
||||
items = append(items,
|
||||
c.Contracts[constants.NetmapContract].Hash,
|
||||
c.Contracts[constants.BalanceContract].Hash,
|
||||
c.Contracts[constants.FrostfsIDContract].Hash,
|
||||
nnsCs.Hash,
|
||||
"container")
|
||||
case constants.FrostfsIDContract:
|
||||
var (
|
||||
h util.Uint160
|
||||
found bool
|
||||
err error
|
||||
)
|
||||
if method == constants.UpdateMethodName {
|
||||
h, found, err = getFrostfsIDAdminFromContract(c.ReadOnlyInvoker)
|
||||
}
|
||||
if method != constants.UpdateMethodName || err == nil && !found {
|
||||
h, found, err = getFrostfsIDAdmin(viper.GetViper())
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if found {
|
||||
items = append(items, h)
|
||||
} else {
|
||||
items = append(items, c.Contracts[constants.ProxyContract].Hash)
|
||||
}
|
||||
case constants.NetmapContract:
|
||||
md := GetDefaultNetmapContractConfigMap()
|
||||
if method == constants.UpdateMethodName {
|
||||
if err := MergeNetmapConfig(c.ReadOnlyInvoker, md); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
var configParam []any
|
||||
for k, v := range md {
|
||||
configParam = append(configParam, k, v)
|
||||
}
|
||||
|
||||
items = append(items,
|
||||
c.Contracts[constants.BalanceContract].Hash,
|
||||
c.Contracts[constants.ContainerContract].Hash,
|
||||
keysParam,
|
||||
configParam)
|
||||
case constants.ProxyContract:
|
||||
items = nil
|
||||
case constants.PolicyContract:
|
||||
items = append(items, c.Contracts[constants.ProxyContract].Hash)
|
||||
default:
|
||||
panic("invalid contract name: " + ctrName)
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func GetContractDeployParameters(cs *ContractState, deployData []any) []any {
|
||||
return []any{cs.RawNEF, cs.RawManifest, deployData}
|
||||
}
|
||||
|
||||
func DeployNNS(c *InitializeContext, method string) error {
|
||||
cs := c.GetContract(constants.NNSContract)
|
||||
h := cs.Hash
|
||||
|
||||
nnsCs, err := c.NNSContractState()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if nnsCs != nil {
|
||||
if nnsCs.NEF.Checksum == cs.NEF.Checksum {
|
||||
if method == constants.DeployMethodName {
|
||||
c.Command.Println("NNS contract is already deployed.")
|
||||
} else {
|
||||
c.Command.Println("NNS contract is already updated.")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
h = nnsCs.Hash
|
||||
}
|
||||
|
||||
err = AddManifestGroup(c.ContractWallet, h, cs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't sign manifest group: %v", err)
|
||||
}
|
||||
|
||||
params := GetContractDeployParameters(cs, nil)
|
||||
|
||||
invokeHash := management.Hash
|
||||
if method == constants.UpdateMethodName {
|
||||
invokeHash = nnsCs.Hash
|
||||
}
|
||||
|
||||
tx, err := c.CommitteeAct.MakeCall(invokeHash, method, params...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create deploy tx for %s: %w", constants.NNSContract, err)
|
||||
}
|
||||
|
||||
if err := c.MultiSignAndSend(tx, constants.CommitteeAccountName); err != nil {
|
||||
return fmt.Errorf("can't send deploy transaction: %w", err)
|
||||
}
|
||||
|
||||
c.Command.Println("NNS hash:", invokeHash.StringLE())
|
||||
return c.AwaitTx()
|
||||
}
|
83
cmd/frostfs-adm/internal/modules/morph/helper/download.go
Normal file
83
cmd/frostfs-adm/internal/modules/morph/helper/download.go
Normal file
|
@ -0,0 +1,83 @@
|
|||
package helper
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"code.gitea.io/sdk/gitea"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var errNoReleasesFound = errors.New("attempt to fetch contracts archive from the offitial repository failed: no releases found")
|
||||
|
||||
func downloadContracts(cmd *cobra.Command, url string) (io.ReadCloser, error) {
|
||||
cmd.Printf("Downloading contracts archive from '%s'\n", url)
|
||||
|
||||
// HTTP client with connect timeout
|
||||
client := http.Client{
|
||||
Transport: &http.Transport{
|
||||
DialContext: (&net.Dialer{
|
||||
Timeout: 10 * time.Second,
|
||||
}).DialContext,
|
||||
},
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(cmd.Context(), 60*time.Second)
|
||||
defer cancel()
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't create request: %w", err)
|
||||
}
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't fetch contracts archive: %w", err)
|
||||
}
|
||||
return resp.Body, nil
|
||||
}
|
||||
|
||||
func downloadContractsFromRepository(cmd *cobra.Command) (io.ReadCloser, error) {
|
||||
client, err := gitea.NewClient("https://git.frostfs.info")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't initialize repository client: %w", err)
|
||||
}
|
||||
|
||||
releases, _, err := client.ListReleases("TrueCloudLab", "frostfs-contract", gitea.ListReleasesOptions{})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't fetch release information: %w", err)
|
||||
}
|
||||
|
||||
var latestRelease *gitea.Release
|
||||
for _, r := range releases {
|
||||
if !r.IsDraft && !r.IsPrerelease {
|
||||
latestRelease = r
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if latestRelease == nil {
|
||||
return nil, errNoReleasesFound
|
||||
}
|
||||
|
||||
cmd.Printf("Found release %s (%s)\n", latestRelease.TagName, latestRelease.Title)
|
||||
|
||||
var url string
|
||||
for _, a := range latestRelease.Attachments {
|
||||
if strings.HasPrefix(a.Name, "frostfs-contract") {
|
||||
url = a.DownloadURL
|
||||
break
|
||||
}
|
||||
}
|
||||
if url == "" {
|
||||
return nil, errors.New("can't find contracts archive in the latest release")
|
||||
}
|
||||
|
||||
return downloadContracts(cmd, url)
|
||||
}
|
35
cmd/frostfs-adm/internal/modules/morph/helper/frostfsid.go
Normal file
35
cmd/frostfs-adm/internal/modules/morph/helper/frostfsid.go
Normal file
|
@ -0,0 +1,35 @@
|
|||
package helper
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
|
||||
"github.com/nspcc-dev/neo-go/pkg/encoding/address"
|
||||
"github.com/nspcc-dev/neo-go/pkg/util"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
const frostfsIDAdminConfigKey = "frostfsid.admin"
|
||||
|
||||
func getFrostfsIDAdmin(v *viper.Viper) (util.Uint160, bool, error) {
|
||||
admin := v.GetString(frostfsIDAdminConfigKey)
|
||||
if admin == "" {
|
||||
return util.Uint160{}, false, nil
|
||||
}
|
||||
|
||||
h, err := address.StringToUint160(admin)
|
||||
if err == nil {
|
||||
return h, true, nil
|
||||
}
|
||||
|
||||
h, err = util.Uint160DecodeStringLE(admin)
|
||||
if err == nil {
|
||||
return h, true, nil
|
||||
}
|
||||
|
||||
pk, err := keys.NewPublicKeyFromString(admin)
|
||||
if err == nil {
|
||||
return pk.GetScriptHash(), true, nil
|
||||
}
|
||||
return util.Uint160{}, true, fmt.Errorf("frostfsid: admin is invalid: '%s'", admin)
|
||||
}
|
|
@ -0,0 +1,53 @@
|
|||
package helper
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"testing"
|
||||
|
||||
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
|
||||
"github.com/nspcc-dev/neo-go/pkg/encoding/address"
|
||||
"github.com/spf13/viper"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestFrostfsIDConfig(t *testing.T) {
|
||||
pks := make([]*keys.PrivateKey, 4)
|
||||
for i := range pks {
|
||||
pk, err := keys.NewPrivateKey()
|
||||
require.NoError(t, err)
|
||||
pks[i] = pk
|
||||
}
|
||||
|
||||
fmts := []string{
|
||||
pks[0].GetScriptHash().StringLE(),
|
||||
address.Uint160ToString(pks[1].GetScriptHash()),
|
||||
hex.EncodeToString(pks[2].PublicKey().UncompressedBytes()),
|
||||
hex.EncodeToString(pks[3].PublicKey().Bytes()),
|
||||
}
|
||||
|
||||
for i := range fmts {
|
||||
v := viper.New()
|
||||
v.Set("frostfsid.admin", fmts[i])
|
||||
|
||||
actual, found, err := getFrostfsIDAdmin(v)
|
||||
require.NoError(t, err)
|
||||
require.True(t, found)
|
||||
require.Equal(t, pks[i].GetScriptHash(), actual)
|
||||
}
|
||||
|
||||
t.Run("bad key", func(t *testing.T) {
|
||||
v := viper.New()
|
||||
v.Set("frostfsid.admin", "abc")
|
||||
|
||||
_, found, err := getFrostfsIDAdmin(v)
|
||||
require.Error(t, err)
|
||||
require.True(t, found)
|
||||
})
|
||||
t.Run("missing key", func(t *testing.T) {
|
||||
v := viper.New()
|
||||
|
||||
_, found, err := getFrostfsIDAdmin(v)
|
||||
require.NoError(t, err)
|
||||
require.False(t, found)
|
||||
})
|
||||
}
|
39
cmd/frostfs-adm/internal/modules/morph/helper/group.go
Normal file
39
cmd/frostfs-adm/internal/modules/morph/helper/group.go
Normal file
|
@ -0,0 +1,39 @@
|
|||
package helper
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/nspcc-dev/neo-go/pkg/smartcontract/manifest"
|
||||
"github.com/nspcc-dev/neo-go/pkg/util"
|
||||
"github.com/nspcc-dev/neo-go/pkg/wallet"
|
||||
)
|
||||
|
||||
func AddManifestGroup(cw *wallet.Wallet, h util.Uint160, cs *ContractState) error {
|
||||
priv := cw.Accounts[0].PrivateKey()
|
||||
pub := priv.PublicKey()
|
||||
|
||||
sig := priv.Sign(h.BytesBE())
|
||||
found := false
|
||||
|
||||
for i := range cs.Manifest.Groups {
|
||||
if cs.Manifest.Groups[i].PublicKey.Equal(pub) {
|
||||
cs.Manifest.Groups[i].Signature = sig
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
cs.Manifest.Groups = append(cs.Manifest.Groups, manifest.Group{
|
||||
PublicKey: pub,
|
||||
Signature: sig,
|
||||
})
|
||||
}
|
||||
|
||||
data, err := json.Marshal(cs.Manifest)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cs.RawManifest = data
|
||||
return nil
|
||||
}
|
223
cmd/frostfs-adm/internal/modules/morph/helper/initialize.go
Normal file
223
cmd/frostfs-adm/internal/modules/morph/helper/initialize.go
Normal file
|
@ -0,0 +1,223 @@
|
|||
package helper
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-contract/nns"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/config"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/constants"
|
||||
commonCmd "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/internal/common"
|
||||
"github.com/nspcc-dev/neo-go/pkg/core/native/nativenames"
|
||||
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
|
||||
"github.com/nspcc-dev/neo-go/pkg/encoding/address"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/invoker"
|
||||
nns2 "github.com/nspcc-dev/neo-go/pkg/rpcclient/nns"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/unwrap"
|
||||
"github.com/nspcc-dev/neo-go/pkg/smartcontract/trigger"
|
||||
"github.com/nspcc-dev/neo-go/pkg/util"
|
||||
"github.com/nspcc-dev/neo-go/pkg/vm/stackitem"
|
||||
"github.com/nspcc-dev/neo-go/pkg/vm/vmstate"
|
||||
"github.com/nspcc-dev/neo-go/pkg/wallet"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var ErrTooManyAlphabetNodes = fmt.Errorf("too many alphabet nodes (maximum allowed is %d)", constants.MaxAlphabetNodes)
|
||||
|
||||
func AwaitTx(cmd *cobra.Command, c Client, txs []HashVUBPair) error {
|
||||
cmd.Println("Waiting for transactions to persist...")
|
||||
|
||||
at := trigger.Application
|
||||
|
||||
var retErr error
|
||||
|
||||
loop:
|
||||
for i := range txs {
|
||||
var it int
|
||||
var pollInterval time.Duration
|
||||
var pollIntervalChanged bool
|
||||
for {
|
||||
// We must fetch current height before application log, to avoid race condition.
|
||||
currBlock, err := c.GetBlockCount()
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't fetch current block height: %w", err)
|
||||
}
|
||||
res, err := c.GetApplicationLog(txs[i].Hash, &at)
|
||||
if err == nil {
|
||||
if retErr == nil && len(res.Executions) > 0 && res.Executions[0].VMState != vmstate.Halt {
|
||||
retErr = fmt.Errorf("tx %d persisted in %s state: %s",
|
||||
i, res.Executions[0].VMState, res.Executions[0].FaultException)
|
||||
}
|
||||
continue loop
|
||||
}
|
||||
if txs[i].Vub < currBlock {
|
||||
return fmt.Errorf("tx was not persisted: Vub=%d, height=%d", txs[i].Vub, currBlock)
|
||||
}
|
||||
|
||||
pollInterval, pollIntervalChanged = NextPollInterval(it, pollInterval)
|
||||
if pollIntervalChanged && viper.GetBool(commonflags.Verbose) {
|
||||
cmd.Printf("Pool interval to check transaction persistence changed: %s\n", pollInterval.String())
|
||||
}
|
||||
|
||||
timer := time.NewTimer(pollInterval)
|
||||
select {
|
||||
case <-cmd.Context().Done():
|
||||
return cmd.Context().Err()
|
||||
case <-timer.C:
|
||||
}
|
||||
|
||||
it++
|
||||
}
|
||||
}
|
||||
|
||||
return retErr
|
||||
}
|
||||
|
||||
func NextPollInterval(it int, previous time.Duration) (time.Duration, bool) {
|
||||
const minPollInterval = 1 * time.Second
|
||||
const maxPollInterval = 16 * time.Second
|
||||
const changeAfter = 5
|
||||
if it == 0 {
|
||||
return minPollInterval, true
|
||||
}
|
||||
if it%changeAfter != 0 {
|
||||
return previous, false
|
||||
}
|
||||
nextInterval := previous * 2
|
||||
if nextInterval > maxPollInterval {
|
||||
return maxPollInterval, previous != maxPollInterval
|
||||
}
|
||||
return nextInterval, true
|
||||
}
|
||||
|
||||
func GetWalletAccount(w *wallet.Wallet, typ string) (*wallet.Account, error) {
|
||||
for i := range w.Accounts {
|
||||
if w.Accounts[i].Label == typ {
|
||||
return w.Accounts[i], nil
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("account for '%s' not found", typ)
|
||||
}
|
||||
|
||||
func GetComitteAcc(cmd *cobra.Command, v *viper.Viper) *wallet.Account {
|
||||
walletDir := config.ResolveHomePath(viper.GetString(commonflags.AlphabetWalletsFlag))
|
||||
wallets, err := GetAlphabetWallets(v, walletDir)
|
||||
commonCmd.ExitOnErr(cmd, "unable to get alphabet wallets: %w", err)
|
||||
|
||||
committeeAcc, err := GetWalletAccount(wallets[0], constants.CommitteeAccountName)
|
||||
commonCmd.ExitOnErr(cmd, "can't find committee account: %w", err)
|
||||
return committeeAcc
|
||||
}
|
||||
|
||||
func NNSResolve(inv *invoker.Invoker, nnsHash util.Uint160, domain string) (stackitem.Item, error) {
|
||||
return unwrap.Item(inv.Call(nnsHash, "resolve", domain, int64(nns.TXT)))
|
||||
}
|
||||
|
||||
// ParseNNSResolveResult parses the result of resolving NNS record.
|
||||
// It works with multiple formats (corresponding to multiple NNS versions).
|
||||
// If array of hashes is provided, it returns only the first one.
|
||||
func ParseNNSResolveResult(res stackitem.Item) (util.Uint160, error) {
|
||||
arr, ok := res.Value().([]stackitem.Item)
|
||||
if !ok {
|
||||
arr = []stackitem.Item{res}
|
||||
}
|
||||
if _, ok := res.Value().(stackitem.Null); ok || len(arr) == 0 {
|
||||
return util.Uint160{}, errors.New("NNS record is missing")
|
||||
}
|
||||
for i := range arr {
|
||||
bs, err := arr[i].TryBytes()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// We support several formats for hash encoding, this logic should be maintained in sync
|
||||
// with NNSResolve from pkg/morph/client/nns.go
|
||||
h, err := util.Uint160DecodeStringLE(string(bs))
|
||||
if err == nil {
|
||||
return h, nil
|
||||
}
|
||||
|
||||
h, err = address.StringToUint160(string(bs))
|
||||
if err == nil {
|
||||
return h, nil
|
||||
}
|
||||
}
|
||||
return util.Uint160{}, errors.New("no valid hashes are found")
|
||||
}
|
||||
|
||||
// NNSResolveHash Returns errMissingNNSRecord if invocation fault exception contains "token not found".
|
||||
func NNSResolveHash(inv *invoker.Invoker, nnsHash util.Uint160, domain string) (util.Uint160, error) {
|
||||
item, err := NNSResolve(inv, nnsHash, domain)
|
||||
if err != nil {
|
||||
return util.Uint160{}, err
|
||||
}
|
||||
return ParseNNSResolveResult(item)
|
||||
}
|
||||
|
||||
func DomainOf(contract string) string {
|
||||
return contract + ".frostfs"
|
||||
}
|
||||
|
||||
func NNSResolveKey(inv *invoker.Invoker, nnsHash util.Uint160, domain string) (*keys.PublicKey, error) {
|
||||
res, err := NNSResolve(inv, nnsHash, domain)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, ok := res.Value().(stackitem.Null); ok {
|
||||
return nil, errors.New("NNS record is missing")
|
||||
}
|
||||
arr, ok := res.Value().([]stackitem.Item)
|
||||
if !ok {
|
||||
return nil, errors.New("API of the NNS contract method `resolve` has changed")
|
||||
}
|
||||
for i := range arr {
|
||||
var bs []byte
|
||||
bs, err = arr[i].TryBytes()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
return keys.NewPublicKeyFromString(string(bs))
|
||||
}
|
||||
return nil, errors.New("no valid keys are found")
|
||||
}
|
||||
|
||||
func NNSIsAvailable(c Client, nnsHash util.Uint160, name string) (bool, error) {
|
||||
switch c.(type) {
|
||||
case *rpcclient.Client:
|
||||
inv := invoker.New(c, nil)
|
||||
reader := nns2.NewReader(inv, nnsHash)
|
||||
return reader.IsAvailable(name)
|
||||
default:
|
||||
b, err := unwrap.Bool(InvokeFunction(c, nnsHash, "isAvailable", []any{name}, nil))
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("`isAvailable`: invalid response: %w", err)
|
||||
}
|
||||
|
||||
return b, nil
|
||||
}
|
||||
}
|
||||
|
||||
func CheckNotaryEnabled(c Client) error {
|
||||
ns, err := c.GetNativeContracts()
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't get native contract hashes: %w", err)
|
||||
}
|
||||
|
||||
notaryEnabled := false
|
||||
nativeHashes := make(map[string]util.Uint160, len(ns))
|
||||
for i := range ns {
|
||||
if ns[i].Manifest.Name == nativenames.Notary {
|
||||
notaryEnabled = true
|
||||
}
|
||||
nativeHashes[ns[i].Manifest.Name] = ns[i].Hash
|
||||
}
|
||||
if !notaryEnabled {
|
||||
return errors.New("notary contract must be enabled")
|
||||
}
|
||||
return nil
|
||||
}
|
553
cmd/frostfs-adm/internal/modules/morph/helper/initialize_ctx.go
Normal file
553
cmd/frostfs-adm/internal/modules/morph/helper/initialize_ctx.go
Normal file
|
@ -0,0 +1,553 @@
|
|||
package helper
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
io2 "io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-contract/nns"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/config"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/constants"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/innerring"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/morph/client"
|
||||
"github.com/nspcc-dev/neo-go/pkg/core/state"
|
||||
"github.com/nspcc-dev/neo-go/pkg/core/transaction"
|
||||
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
|
||||
"github.com/nspcc-dev/neo-go/pkg/io"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/actor"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/management"
|
||||
"github.com/nspcc-dev/neo-go/pkg/smartcontract/callflag"
|
||||
"github.com/nspcc-dev/neo-go/pkg/smartcontract/context"
|
||||
"github.com/nspcc-dev/neo-go/pkg/smartcontract/manifest"
|
||||
"github.com/nspcc-dev/neo-go/pkg/smartcontract/nef"
|
||||
"github.com/nspcc-dev/neo-go/pkg/util"
|
||||
"github.com/nspcc-dev/neo-go/pkg/vm/emit"
|
||||
"github.com/nspcc-dev/neo-go/pkg/vm/opcode"
|
||||
"github.com/nspcc-dev/neo-go/pkg/vm/vmstate"
|
||||
"github.com/nspcc-dev/neo-go/pkg/wallet"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var (
|
||||
errNegativeDuration = errors.New("epoch duration must be positive")
|
||||
errNegativeSize = errors.New("max object size must be positive")
|
||||
)
|
||||
|
||||
type ContractState struct {
|
||||
NEF *nef.File
|
||||
RawNEF []byte
|
||||
Manifest *manifest.Manifest
|
||||
RawManifest []byte
|
||||
Hash util.Uint160
|
||||
}
|
||||
|
||||
type Cache struct {
|
||||
NNSCs *state.Contract
|
||||
GroupKey *keys.PublicKey
|
||||
}
|
||||
|
||||
type InitializeContext struct {
|
||||
ClientContext
|
||||
Cache
|
||||
// CommitteeAcc is used for retrieving the committee address and the verification script.
|
||||
CommitteeAcc *wallet.Account
|
||||
// ConsensusAcc is used for retrieving the committee address and the verification script.
|
||||
ConsensusAcc *wallet.Account
|
||||
Wallets []*wallet.Wallet
|
||||
// ContractWallet is a wallet for providing the contract group signature.
|
||||
ContractWallet *wallet.Wallet
|
||||
// Accounts contains simple signature accounts in the same order as in Wallets.
|
||||
Accounts []*wallet.Account
|
||||
Contracts map[string]*ContractState
|
||||
Command *cobra.Command
|
||||
ContractPath string
|
||||
ContractURL string
|
||||
}
|
||||
|
||||
func (cs *ContractState) Parse() error {
|
||||
nf, err := nef.FileFromBytes(cs.RawNEF)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't parse NEF file: %w", err)
|
||||
}
|
||||
|
||||
m := new(manifest.Manifest)
|
||||
if err := json.Unmarshal(cs.RawManifest, m); err != nil {
|
||||
return fmt.Errorf("can't parse manifest file: %w", err)
|
||||
}
|
||||
|
||||
cs.NEF = &nf
|
||||
cs.Manifest = m
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewInitializeContext(cmd *cobra.Command, v *viper.Viper) (*InitializeContext, error) {
|
||||
walletDir := config.ResolveHomePath(viper.GetString(commonflags.AlphabetWalletsFlag))
|
||||
wallets, err := GetAlphabetWallets(v, walletDir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
needContracts := cmd.Name() == "update-contracts" || cmd.Name() == "init"
|
||||
|
||||
var w *wallet.Wallet
|
||||
w, err = getWallet(cmd, v, needContracts, walletDir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
c, err := createClient(cmd, v, wallets)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
committeeAcc, err := GetWalletAccount(wallets[0], constants.CommitteeAccountName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't find committee account: %w", err)
|
||||
}
|
||||
|
||||
consensusAcc, err := GetWalletAccount(wallets[0], constants.ConsensusAccountName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't find consensus account: %w", err)
|
||||
}
|
||||
|
||||
if err := validateInit(cmd); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ctrPath, err := getContractsPath(cmd, needContracts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var ctrURL string
|
||||
if needContracts {
|
||||
ctrURL, _ = cmd.Flags().GetString(commonflags.ContractsURLFlag)
|
||||
}
|
||||
|
||||
if err := CheckNotaryEnabled(c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
accounts, err := getSingleAccounts(wallets)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cliCtx, err := defaultClientContext(c, committeeAcc)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("client context: %w", err)
|
||||
}
|
||||
|
||||
initCtx := &InitializeContext{
|
||||
ClientContext: *cliCtx,
|
||||
ConsensusAcc: consensusAcc,
|
||||
CommitteeAcc: committeeAcc,
|
||||
ContractWallet: w,
|
||||
Wallets: wallets,
|
||||
Accounts: accounts,
|
||||
Command: cmd,
|
||||
Contracts: make(map[string]*ContractState),
|
||||
ContractPath: ctrPath,
|
||||
ContractURL: ctrURL,
|
||||
}
|
||||
|
||||
if needContracts {
|
||||
err := readContracts(initCtx, constants.FullContractList)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return initCtx, nil
|
||||
}
|
||||
|
||||
func validateInit(cmd *cobra.Command) error {
|
||||
if cmd.Name() != "init" {
|
||||
return nil
|
||||
}
|
||||
if viper.GetInt64(commonflags.EpochDurationInitFlag) <= 0 {
|
||||
return errNegativeDuration
|
||||
}
|
||||
|
||||
if viper.GetInt64(commonflags.MaxObjectSizeInitFlag) <= 0 {
|
||||
return errNegativeSize
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func createClient(cmd *cobra.Command, v *viper.Viper, wallets []*wallet.Wallet) (Client, error) {
|
||||
var c Client
|
||||
var err error
|
||||
if ldf := cmd.Flags().Lookup(commonflags.LocalDumpFlag); ldf != nil && ldf.Changed {
|
||||
if cmd.Flags().Changed(commonflags.EndpointFlag) {
|
||||
return nil, fmt.Errorf("`%s` and `%s` flags are mutually exclusive", commonflags.EndpointFlag, commonflags.LocalDumpFlag)
|
||||
}
|
||||
c, err = NewLocalClient(cmd, v, wallets, ldf.Value.String())
|
||||
} else {
|
||||
c, err = NewRemoteClient(v)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't create N3 client: %w", err)
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func getContractsPath(cmd *cobra.Command, needContracts bool) (string, error) {
|
||||
if !needContracts {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
ctrPath, err := cmd.Flags().GetString(commonflags.ContractsInitFlag)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("invalid contracts path: %w", err)
|
||||
}
|
||||
return ctrPath, nil
|
||||
}
|
||||
|
||||
func getSingleAccounts(wallets []*wallet.Wallet) ([]*wallet.Account, error) {
|
||||
accounts := make([]*wallet.Account, len(wallets))
|
||||
for i, w := range wallets {
|
||||
acc, err := GetWalletAccount(w, constants.SingleAccountName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("wallet %s is invalid (no single account): %w", w.Path(), err)
|
||||
}
|
||||
accounts[i] = acc
|
||||
}
|
||||
return accounts, nil
|
||||
}
|
||||
|
||||
func readContracts(c *InitializeContext, names []string) error {
|
||||
var (
|
||||
fi os.FileInfo
|
||||
err error
|
||||
)
|
||||
if c.ContractPath != "" {
|
||||
fi, err = os.Stat(c.ContractPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid contracts path: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if c.ContractPath != "" && fi.IsDir() {
|
||||
for _, ctrName := range names {
|
||||
cs, err := ReadContract(filepath.Join(c.ContractPath, ctrName), ctrName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.Contracts[ctrName] = cs
|
||||
}
|
||||
} else {
|
||||
var r io2.ReadCloser
|
||||
if c.ContractPath != "" {
|
||||
r, err = os.Open(c.ContractPath)
|
||||
} else if c.ContractURL != "" {
|
||||
r, err = downloadContracts(c.Command, c.ContractURL)
|
||||
} else {
|
||||
r, err = downloadContractsFromRepository(c.Command)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't open contracts archive: %w", err)
|
||||
}
|
||||
defer r.Close()
|
||||
|
||||
m, err := readContractsFromArchive(r, names)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, name := range names {
|
||||
if err := m[name].Parse(); err != nil {
|
||||
return err
|
||||
}
|
||||
c.Contracts[name] = m[name]
|
||||
}
|
||||
}
|
||||
|
||||
for _, ctrName := range names {
|
||||
if ctrName != constants.AlphabetContract {
|
||||
cs := c.Contracts[ctrName]
|
||||
cs.Hash = state.CreateContractHash(c.CommitteeAcc.Contract.ScriptHash(),
|
||||
cs.NEF.Checksum, cs.Manifest.Name)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *InitializeContext) Close() {
|
||||
if local, ok := c.Client.(*LocalClient); ok {
|
||||
err := local.Dump()
|
||||
if err != nil {
|
||||
c.Command.PrintErrf("Can't write dump: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *InitializeContext) AwaitTx() error {
|
||||
return c.ClientContext.AwaitTx(c.Command)
|
||||
}
|
||||
|
||||
func (c *InitializeContext) NNSContractState() (*state.Contract, error) {
|
||||
if c.NNSCs != nil {
|
||||
return c.NNSCs, nil
|
||||
}
|
||||
|
||||
r := management.NewReader(c.ReadOnlyInvoker)
|
||||
cs, err := r.GetContractByID(1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
c.NNSCs = cs
|
||||
return cs, nil
|
||||
}
|
||||
|
||||
func (c *InitializeContext) GetSigner(tryGroup bool, acc *wallet.Account) transaction.Signer {
|
||||
if tryGroup && c.GroupKey != nil {
|
||||
return transaction.Signer{
|
||||
Account: acc.Contract.ScriptHash(),
|
||||
Scopes: transaction.CustomGroups,
|
||||
AllowedGroups: keys.PublicKeys{c.GroupKey},
|
||||
}
|
||||
}
|
||||
|
||||
signer := transaction.Signer{
|
||||
Account: acc.Contract.ScriptHash(),
|
||||
Scopes: transaction.Global, // Scope is important, as we have nested call to container contract.
|
||||
}
|
||||
|
||||
if !tryGroup {
|
||||
return signer
|
||||
}
|
||||
|
||||
nnsCs, err := c.NNSContractState()
|
||||
if err != nil {
|
||||
return signer
|
||||
}
|
||||
|
||||
groupKey, err := NNSResolveKey(c.ReadOnlyInvoker, nnsCs.Hash, client.NNSGroupKeyName)
|
||||
if err == nil {
|
||||
c.GroupKey = groupKey
|
||||
|
||||
signer.Scopes = transaction.CustomGroups
|
||||
signer.AllowedGroups = keys.PublicKeys{groupKey}
|
||||
}
|
||||
return signer
|
||||
}
|
||||
|
||||
// SendCommitteeTx creates transaction from script, signs it by committee nodes and sends it to RPC.
|
||||
// If tryGroup is false, global scope is used for the signer (useful when
|
||||
// working with native contracts).
|
||||
func (c *InitializeContext) SendCommitteeTx(script []byte, tryGroup bool) error {
|
||||
return c.sendMultiTx(script, tryGroup, false)
|
||||
}
|
||||
|
||||
// SendConsensusTx creates transaction from script, signs it by alphabet nodes and sends it to RPC.
|
||||
// Not that because this is used only after the contracts were initialized and deployed,
|
||||
// we always try to have a group scope.
|
||||
func (c *InitializeContext) SendConsensusTx(script []byte) error {
|
||||
return c.sendMultiTx(script, true, true)
|
||||
}
|
||||
|
||||
func (c *InitializeContext) sendMultiTx(script []byte, tryGroup bool, withConsensus bool) error {
|
||||
var act *actor.Actor
|
||||
var err error
|
||||
|
||||
withConsensus = withConsensus && !c.ConsensusAcc.Contract.ScriptHash().Equals(c.CommitteeAcc.ScriptHash())
|
||||
if tryGroup {
|
||||
// Even for consensus signatures we need the committee to pay.
|
||||
signers := make([]actor.SignerAccount, 1, 2)
|
||||
signers[0] = actor.SignerAccount{
|
||||
Signer: c.GetSigner(tryGroup, c.CommitteeAcc),
|
||||
Account: c.CommitteeAcc,
|
||||
}
|
||||
if withConsensus {
|
||||
signers = append(signers, actor.SignerAccount{
|
||||
Signer: c.GetSigner(tryGroup, c.ConsensusAcc),
|
||||
Account: c.ConsensusAcc,
|
||||
})
|
||||
}
|
||||
act, err = actor.New(c.Client, signers)
|
||||
} else {
|
||||
if withConsensus {
|
||||
panic("BUG: should never happen")
|
||||
}
|
||||
act, err = c.CommitteeAct, nil
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("could not create actor: %w", err)
|
||||
}
|
||||
|
||||
tx, err := act.MakeUnsignedRun(script, []transaction.Attribute{{Type: transaction.HighPriority}})
|
||||
if err != nil {
|
||||
return fmt.Errorf("could not perform test invocation: %w", err)
|
||||
}
|
||||
|
||||
if err := c.MultiSign(tx, constants.CommitteeAccountName); err != nil {
|
||||
return err
|
||||
}
|
||||
if withConsensus {
|
||||
if err := c.MultiSign(tx, constants.ConsensusAccountName); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return c.SendTx(tx, c.Command, false)
|
||||
}
|
||||
|
||||
func (c *InitializeContext) MultiSignAndSend(tx *transaction.Transaction, accType string) error {
|
||||
if err := c.MultiSign(tx, accType); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.SendTx(tx, c.Command, false)
|
||||
}
|
||||
|
||||
func (c *InitializeContext) MultiSign(tx *transaction.Transaction, accType string) error {
|
||||
version, err := c.Client.GetVersion()
|
||||
if err != nil {
|
||||
// error appears only if client
|
||||
// has not been initialized
|
||||
panic(err)
|
||||
}
|
||||
network := version.Protocol.Network
|
||||
|
||||
// Use parameter context to avoid dealing with signature order.
|
||||
pc := context.NewParameterContext("", network, tx)
|
||||
h := c.CommitteeAcc.Contract.ScriptHash()
|
||||
if accType == constants.ConsensusAccountName {
|
||||
h = c.ConsensusAcc.Contract.ScriptHash()
|
||||
}
|
||||
for _, w := range c.Wallets {
|
||||
acc, err := GetWalletAccount(w, accType)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't find %s wallet account: %w", accType, err)
|
||||
}
|
||||
|
||||
priv := acc.PrivateKey()
|
||||
sign := priv.SignHashable(uint32(network), tx)
|
||||
if err := pc.AddSignature(h, acc.Contract, priv.PublicKey(), sign); err != nil {
|
||||
return fmt.Errorf("can't add signature: %w", err)
|
||||
}
|
||||
if len(pc.Items[h].Signatures) == len(acc.Contract.Parameters) {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
w, err := pc.GetWitness(h)
|
||||
if err != nil {
|
||||
return fmt.Errorf("incomplete signature: %w", err)
|
||||
}
|
||||
|
||||
for i := range tx.Signers {
|
||||
if tx.Signers[i].Account == h {
|
||||
if i < len(tx.Scripts) {
|
||||
tx.Scripts[i] = *w
|
||||
} else if i == len(tx.Scripts) {
|
||||
tx.Scripts = append(tx.Scripts, *w)
|
||||
} else {
|
||||
panic("BUG: invalid signing order")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("%s account was not found among transaction signers", accType)
|
||||
}
|
||||
|
||||
// EmitUpdateNNSGroupScript emits script for updating group key stored in NNS.
|
||||
// First return value is true iff the key is already there and nothing should be done.
|
||||
// Second return value is true iff a domain registration code was emitted.
|
||||
func (c *InitializeContext) EmitUpdateNNSGroupScript(bw *io.BufBinWriter, nnsHash util.Uint160, pub *keys.PublicKey) (bool, bool, error) {
|
||||
isAvail, err := NNSIsAvailable(c.Client, nnsHash, client.NNSGroupKeyName)
|
||||
if err != nil {
|
||||
return false, false, err
|
||||
}
|
||||
|
||||
if !isAvail {
|
||||
currentPub, err := NNSResolveKey(c.ReadOnlyInvoker, nnsHash, client.NNSGroupKeyName)
|
||||
if err != nil {
|
||||
return false, false, err
|
||||
}
|
||||
|
||||
if pub.Equal(currentPub) {
|
||||
return true, false, nil
|
||||
}
|
||||
}
|
||||
|
||||
if isAvail {
|
||||
emit.AppCall(bw.BinWriter, nnsHash, "register", callflag.All,
|
||||
client.NNSGroupKeyName, c.CommitteeAcc.Contract.ScriptHash(),
|
||||
constants.FrostfsOpsEmail, constants.NNSRefreshDefVal, constants.NNSRetryDefVal,
|
||||
int64(constants.DefaultExpirationTime), constants.NNSTtlDefVal)
|
||||
emit.Opcodes(bw.BinWriter, opcode.ASSERT)
|
||||
}
|
||||
|
||||
emit.AppCall(bw.BinWriter, nnsHash, "deleteRecords", callflag.All, "group.frostfs", int64(nns.TXT))
|
||||
emit.AppCall(bw.BinWriter, nnsHash, "addRecord", callflag.All,
|
||||
"group.frostfs", int64(nns.TXT), hex.EncodeToString(pub.Bytes()))
|
||||
|
||||
return false, isAvail, nil
|
||||
}
|
||||
|
||||
func (c *InitializeContext) NNSRegisterDomainScript(nnsHash, expectedHash util.Uint160, domain string) ([]byte, bool, error) {
|
||||
ok, err := NNSIsAvailable(c.Client, nnsHash, domain)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
|
||||
if ok {
|
||||
bw := io.NewBufBinWriter()
|
||||
emit.AppCall(bw.BinWriter, nnsHash, "register", callflag.All,
|
||||
domain, c.CommitteeAcc.Contract.ScriptHash(),
|
||||
constants.FrostfsOpsEmail, constants.NNSRefreshDefVal, constants.NNSRetryDefVal,
|
||||
int64(constants.DefaultExpirationTime), constants.NNSTtlDefVal)
|
||||
emit.Opcodes(bw.BinWriter, opcode.ASSERT)
|
||||
|
||||
if bw.Err != nil {
|
||||
panic(bw.Err)
|
||||
}
|
||||
return bw.Bytes(), false, nil
|
||||
}
|
||||
|
||||
s, err := NNSResolveHash(c.ReadOnlyInvoker, nnsHash, domain)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
return nil, s == expectedHash, nil
|
||||
}
|
||||
|
||||
func (c *InitializeContext) NNSRootRegistered(nnsHash util.Uint160, zone string) (bool, error) {
|
||||
res, err := c.CommitteeAct.Call(nnsHash, "isAvailable", "name."+zone)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
return res.State == vmstate.Halt.String(), nil
|
||||
}
|
||||
|
||||
func (c *InitializeContext) IsUpdated(ctrHash util.Uint160, cs *ContractState) bool {
|
||||
r := management.NewReader(c.ReadOnlyInvoker)
|
||||
realCs, err := r.GetContract(ctrHash)
|
||||
return err == nil && realCs != nil && realCs.NEF.Checksum == cs.NEF.Checksum
|
||||
}
|
||||
|
||||
func (c *InitializeContext) GetContract(ctrName string) *ContractState {
|
||||
return c.Contracts[ctrName]
|
||||
}
|
||||
|
||||
func (c *InitializeContext) GetAlphabetDeployItems(i, n int) []any {
|
||||
items := make([]any, 5)
|
||||
items[0] = c.Contracts[constants.NetmapContract].Hash
|
||||
items[1] = c.Contracts[constants.ProxyContract].Hash
|
||||
items[2] = innerring.GlagoliticLetter(i).String()
|
||||
items[3] = int64(i)
|
||||
items[4] = int64(n)
|
||||
return items
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package helper
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestNextPollInterval(t *testing.T) {
|
||||
var pollInterval time.Duration
|
||||
var iteration int
|
||||
|
||||
pollInterval, hasChanged := NextPollInterval(iteration, pollInterval)
|
||||
require.True(t, hasChanged)
|
||||
require.Equal(t, time.Second, pollInterval)
|
||||
|
||||
iteration = 4
|
||||
pollInterval, hasChanged = NextPollInterval(iteration, pollInterval)
|
||||
require.False(t, hasChanged)
|
||||
require.Equal(t, time.Second, pollInterval)
|
||||
|
||||
iteration = 5
|
||||
pollInterval, hasChanged = NextPollInterval(iteration, pollInterval)
|
||||
require.True(t, hasChanged)
|
||||
require.Equal(t, 2*time.Second, pollInterval)
|
||||
|
||||
iteration = 10
|
||||
pollInterval, hasChanged = NextPollInterval(iteration, pollInterval)
|
||||
require.True(t, hasChanged)
|
||||
require.Equal(t, 4*time.Second, pollInterval)
|
||||
|
||||
iteration = 20
|
||||
pollInterval = 32 * time.Second
|
||||
pollInterval, hasChanged = NextPollInterval(iteration, pollInterval)
|
||||
require.True(t, hasChanged) // from 32s to 16s
|
||||
require.Equal(t, 16*time.Second, pollInterval)
|
||||
|
||||
pollInterval = 16 * time.Second
|
||||
pollInterval, hasChanged = NextPollInterval(iteration, pollInterval)
|
||||
require.False(t, hasChanged)
|
||||
require.Equal(t, 16*time.Second, pollInterval)
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package morph
|
||||
package helper
|
||||
|
||||
import (
|
||||
"crypto/elliptic"
|
||||
|
@ -8,6 +8,8 @@ import (
|
|||
"sort"
|
||||
"time"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/constants"
|
||||
"github.com/google/uuid"
|
||||
"github.com/nspcc-dev/neo-go/pkg/config"
|
||||
"github.com/nspcc-dev/neo-go/pkg/core"
|
||||
|
@ -38,16 +40,15 @@ import (
|
|||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
type localClient struct {
|
||||
type LocalClient struct {
|
||||
bc *core.Blockchain
|
||||
transactions []*transaction.Transaction
|
||||
dumpPath string
|
||||
accounts []*wallet.Account
|
||||
maxGasInvoke int64
|
||||
}
|
||||
|
||||
func newLocalClient(cmd *cobra.Command, v *viper.Viper, wallets []*wallet.Wallet, dumpPath string) (*localClient, error) {
|
||||
cfg, err := config.LoadFile(v.GetString(protoConfigPath))
|
||||
func NewLocalClient(cmd *cobra.Command, v *viper.Viper, wallets []*wallet.Wallet, dumpPath string) (*LocalClient, error) {
|
||||
cfg, err := config.LoadFile(v.GetString(commonflags.ProtoConfigPath))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
@ -57,17 +58,59 @@ func newLocalClient(cmd *cobra.Command, v *viper.Viper, wallets []*wallet.Wallet
|
|||
return nil, err
|
||||
}
|
||||
|
||||
m := smartcontract.GetDefaultHonestNodeCount(int(cfg.ProtocolConfiguration.ValidatorsCount))
|
||||
accounts := make([]*wallet.Account, len(wallets))
|
||||
for i := range accounts {
|
||||
accounts[i], err = getWalletAccount(wallets[i], consensusAccountName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
go bc.Run()
|
||||
|
||||
accounts, err := getBlockSigningAccounts(cfg.ProtocolConfiguration, wallets)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if cmd.Name() != "init" {
|
||||
if err := restoreDump(bc, dumpPath); err != nil {
|
||||
return nil, fmt.Errorf("restore dump: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return &LocalClient{
|
||||
bc: bc,
|
||||
dumpPath: dumpPath,
|
||||
accounts: accounts,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func restoreDump(bc *core.Blockchain, dumpPath string) error {
|
||||
f, err := os.OpenFile(dumpPath, os.O_RDONLY, 0o600)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't open local dump: %w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
r := io.NewBinReaderFromIO(f)
|
||||
|
||||
var skip uint32
|
||||
if bc.BlockHeight() != 0 {
|
||||
skip = bc.BlockHeight() + 1
|
||||
}
|
||||
|
||||
count := r.ReadU32LE() - skip
|
||||
if err := chaindump.Restore(bc, r, skip, count, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func getBlockSigningAccounts(cfg config.ProtocolConfiguration, wallets []*wallet.Wallet) ([]*wallet.Account, error) {
|
||||
accounts := make([]*wallet.Account, len(wallets))
|
||||
for i := range accounts {
|
||||
acc, err := GetWalletAccount(wallets[i], constants.ConsensusAccountName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
accounts[i] = acc
|
||||
}
|
||||
|
||||
indexMap := make(map[string]int)
|
||||
for i, pub := range cfg.ProtocolConfiguration.StandbyCommittee {
|
||||
for i, pub := range cfg.StandbyCommittee {
|
||||
indexMap[pub] = i
|
||||
}
|
||||
|
||||
|
@ -76,49 +119,23 @@ func newLocalClient(cmd *cobra.Command, v *viper.Viper, wallets []*wallet.Wallet
|
|||
pj := accounts[j].PrivateKey().PublicKey().Bytes()
|
||||
return indexMap[string(pi)] < indexMap[string(pj)]
|
||||
})
|
||||
sort.Slice(accounts[:cfg.ProtocolConfiguration.ValidatorsCount], func(i, j int) bool {
|
||||
sort.Slice(accounts[:cfg.ValidatorsCount], func(i, j int) bool {
|
||||
return accounts[i].PublicKey().Cmp(accounts[j].PublicKey()) == -1
|
||||
})
|
||||
|
||||
go bc.Run()
|
||||
|
||||
if cmd.Name() != "init" {
|
||||
f, err := os.OpenFile(dumpPath, os.O_RDONLY, 0o600)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't open local dump: %w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
r := io.NewBinReaderFromIO(f)
|
||||
|
||||
var skip uint32
|
||||
if bc.BlockHeight() != 0 {
|
||||
skip = bc.BlockHeight() + 1
|
||||
}
|
||||
|
||||
count := r.ReadU32LE() - skip
|
||||
if err := chaindump.Restore(bc, r, skip, count, nil); err != nil {
|
||||
return nil, fmt.Errorf("can't restore local dump: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return &localClient{
|
||||
bc: bc,
|
||||
dumpPath: dumpPath,
|
||||
accounts: accounts[:m],
|
||||
maxGasInvoke: 15_0000_0000,
|
||||
}, nil
|
||||
m := smartcontract.GetDefaultHonestNodeCount(int(cfg.ValidatorsCount))
|
||||
return accounts[:m], nil
|
||||
}
|
||||
|
||||
func (l *localClient) GetBlockCount() (uint32, error) {
|
||||
func (l *LocalClient) GetBlockCount() (uint32, error) {
|
||||
return l.bc.BlockHeight(), nil
|
||||
}
|
||||
|
||||
func (l *localClient) GetNativeContracts() ([]state.NativeContract, error) {
|
||||
func (l *LocalClient) GetNativeContracts() ([]state.Contract, error) {
|
||||
return l.bc.GetNatives(), nil
|
||||
}
|
||||
|
||||
func (l *localClient) GetApplicationLog(h util.Uint256, t *trigger.Type) (*result.ApplicationLog, error) {
|
||||
func (l *LocalClient) GetApplicationLog(h util.Uint256, t *trigger.Type) (*result.ApplicationLog, error) {
|
||||
aer, err := l.bc.GetAppExecResults(h, *t)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
@ -128,13 +145,8 @@ func (l *localClient) GetApplicationLog(h util.Uint256, t *trigger.Type) (*resul
|
|||
return &a, nil
|
||||
}
|
||||
|
||||
func (l *localClient) GetCommittee() (keys.PublicKeys, error) {
|
||||
// not used by `morph init` command
|
||||
panic("unexpected call")
|
||||
}
|
||||
|
||||
// InvokeFunction is implemented via `InvokeScript`.
|
||||
func (l *localClient) InvokeFunction(h util.Uint160, method string, sPrm []smartcontract.Parameter, ss []transaction.Signer) (*result.Invoke, error) {
|
||||
func (l *LocalClient) InvokeFunction(h util.Uint160, method string, sPrm []smartcontract.Parameter, ss []transaction.Signer) (*result.Invoke, error) {
|
||||
var err error
|
||||
|
||||
pp := make([]any, len(sPrm))
|
||||
|
@ -145,21 +157,21 @@ func (l *localClient) InvokeFunction(h util.Uint160, method string, sPrm []smart
|
|||
}
|
||||
}
|
||||
|
||||
return invokeFunction(l, h, method, pp, ss)
|
||||
return InvokeFunction(l, h, method, pp, ss)
|
||||
}
|
||||
|
||||
func (l *localClient) TerminateSession(_ uuid.UUID) (bool, error) {
|
||||
func (l *LocalClient) TerminateSession(_ uuid.UUID) (bool, error) {
|
||||
// not used by `morph init` command
|
||||
panic("unexpected call")
|
||||
}
|
||||
|
||||
func (l *localClient) TraverseIterator(_, _ uuid.UUID, _ int) ([]stackitem.Item, error) {
|
||||
func (l *LocalClient) TraverseIterator(_, _ uuid.UUID, _ int) ([]stackitem.Item, error) {
|
||||
// not used by `morph init` command
|
||||
panic("unexpected call")
|
||||
}
|
||||
|
||||
// GetVersion return default version.
|
||||
func (l *localClient) GetVersion() (*result.Version, error) {
|
||||
func (l *LocalClient) GetVersion() (*result.Version, error) {
|
||||
c := l.bc.GetConfig()
|
||||
return &result.Version{
|
||||
Protocol: result.Protocol{
|
||||
|
@ -180,7 +192,7 @@ func (l *localClient) GetVersion() (*result.Version, error) {
|
|||
}, nil
|
||||
}
|
||||
|
||||
func (l *localClient) InvokeContractVerify(util.Uint160, []smartcontract.Parameter, []transaction.Signer, ...transaction.Witness) (*result.Invoke, error) {
|
||||
func (l *LocalClient) InvokeContractVerify(util.Uint160, []smartcontract.Parameter, []transaction.Signer, ...transaction.Witness) (*result.Invoke, error) {
|
||||
// not used by `morph init` command
|
||||
panic("unexpected call")
|
||||
}
|
||||
|
@ -188,7 +200,7 @@ func (l *localClient) InvokeContractVerify(util.Uint160, []smartcontract.Paramet
|
|||
// CalculateNetworkFee calculates network fee for the given transaction.
|
||||
// Copied from neo-go with minor corrections (no need to support non-notary mode):
|
||||
// https://github.com/nspcc-dev/neo-go/blob/v0.103.0/pkg/services/rpcsrv/server.go#L911
|
||||
func (l *localClient) CalculateNetworkFee(tx *transaction.Transaction) (int64, error) {
|
||||
func (l *LocalClient) CalculateNetworkFee(tx *transaction.Transaction) (int64, error) {
|
||||
// Avoid setting hash for this tx: server code doesn't touch client transaction.
|
||||
data := tx.Bytes()
|
||||
tx, err := transaction.NewTransactionFromBytes(data)
|
||||
|
@ -225,7 +237,7 @@ func (l *localClient) CalculateNetworkFee(tx *transaction.Transaction) (int64, e
|
|||
paramz = []manifest.Parameter{{Type: smartcontract.SignatureType}}
|
||||
} else if nSigs, _, ok := vm.ParseMultiSigContract(w.VerificationScript); ok {
|
||||
paramz = make([]manifest.Parameter, nSigs)
|
||||
for j := 0; j < nSigs; j++ {
|
||||
for j := range nSigs {
|
||||
paramz[j] = manifest.Parameter{Type: smartcontract.SignatureType}
|
||||
}
|
||||
}
|
||||
|
@ -259,7 +271,7 @@ func (l *localClient) CalculateNetworkFee(tx *transaction.Transaction) (int64, e
|
|||
return netFee, nil
|
||||
}
|
||||
|
||||
func (l *localClient) InvokeScript(script []byte, signers []transaction.Signer) (*result.Invoke, error) {
|
||||
func (l *LocalClient) InvokeScript(script []byte, signers []transaction.Signer) (*result.Invoke, error) {
|
||||
lastBlock, err := l.bc.GetBlock(l.bc.CurrentBlockHash())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
@ -295,19 +307,13 @@ func (l *localClient) InvokeScript(script []byte, signers []transaction.Signer)
|
|||
}, nil
|
||||
}
|
||||
|
||||
func (l *localClient) SendRawTransaction(tx *transaction.Transaction) (util.Uint256, error) {
|
||||
// We need to test that transaction was formed correctly to catch as many errors as we can.
|
||||
bs := tx.Bytes()
|
||||
_, err := transaction.NewTransactionFromBytes(bs)
|
||||
if err != nil {
|
||||
return tx.Hash(), fmt.Errorf("invalid transaction: %w", err)
|
||||
}
|
||||
|
||||
func (l *LocalClient) SendRawTransaction(tx *transaction.Transaction) (util.Uint256, error) {
|
||||
tx = tx.Copy()
|
||||
l.transactions = append(l.transactions, tx)
|
||||
return tx.Hash(), nil
|
||||
}
|
||||
|
||||
func (l *localClient) putTransactions() error {
|
||||
func (l *LocalClient) putTransactions() error {
|
||||
// 1. Prepare new block.
|
||||
lastBlock, err := l.bc.GetBlock(l.bc.CurrentBlockHash())
|
||||
if err != nil {
|
||||
|
@ -349,7 +355,7 @@ func (l *localClient) putTransactions() error {
|
|||
return l.bc.AddBlock(b)
|
||||
}
|
||||
|
||||
func invokeFunction(c Client, h util.Uint160, method string, parameters []any, signers []transaction.Signer) (*result.Invoke, error) {
|
||||
func InvokeFunction(c Client, h util.Uint160, method string, parameters []any, signers []transaction.Signer) (*result.Invoke, error) {
|
||||
w := io.NewBufBinWriter()
|
||||
emit.Array(w.BinWriter, parameters...)
|
||||
emit.AppCallNoArgs(w.BinWriter, h, method, callflag.All)
|
||||
|
@ -361,7 +367,7 @@ func invokeFunction(c Client, h util.Uint160, method string, parameters []any, s
|
|||
|
||||
var errGetDesignatedByRoleResponse = errors.New("`getDesignatedByRole`: invalid response")
|
||||
|
||||
func getDesignatedByRole(inv *invoker.Invoker, h util.Uint160, role noderoles.Role, u uint32) (keys.PublicKeys, error) {
|
||||
func GetDesignatedByRole(inv *invoker.Invoker, h util.Uint160, role noderoles.Role, u uint32) (keys.PublicKeys, error) {
|
||||
arr, err := unwrap.Array(inv.Call(h, "getDesignatedByRole", int64(role), int64(u)))
|
||||
if err != nil {
|
||||
return nil, errGetDesignatedByRoleResponse
|
||||
|
@ -382,7 +388,7 @@ func getDesignatedByRole(inv *invoker.Invoker, h util.Uint160, role noderoles.Ro
|
|||
return pubs, nil
|
||||
}
|
||||
|
||||
func (l *localClient) dump() (err error) {
|
||||
func (l *LocalClient) Dump() (err error) {
|
||||
defer l.bc.Close()
|
||||
|
||||
f, err := os.Create(l.dumpPath)
|
|
@ -1,14 +1,15 @@
|
|||
package morph
|
||||
package helper
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
"github.com/nspcc-dev/neo-go/pkg/core/state"
|
||||
"github.com/nspcc-dev/neo-go/pkg/core/transaction"
|
||||
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
|
||||
"github.com/nspcc-dev/neo-go/pkg/neorpc/result"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/actor"
|
||||
|
@ -23,30 +24,25 @@ import (
|
|||
// Client represents N3 client interface capable of test-invoking scripts
|
||||
// and sending signed transactions to chain.
|
||||
type Client interface {
|
||||
invoker.RPCInvoke
|
||||
actor.RPCActor
|
||||
|
||||
GetBlockCount() (uint32, error)
|
||||
GetNativeContracts() ([]state.NativeContract, error)
|
||||
GetNativeContracts() ([]state.Contract, error)
|
||||
GetApplicationLog(util.Uint256, *trigger.Type) (*result.ApplicationLog, error)
|
||||
GetVersion() (*result.Version, error)
|
||||
SendRawTransaction(*transaction.Transaction) (util.Uint256, error)
|
||||
GetCommittee() (keys.PublicKeys, error)
|
||||
CalculateNetworkFee(tx *transaction.Transaction) (int64, error)
|
||||
}
|
||||
|
||||
type hashVUBPair struct {
|
||||
hash util.Uint256
|
||||
vub uint32
|
||||
type HashVUBPair struct {
|
||||
Hash util.Uint256
|
||||
Vub uint32
|
||||
}
|
||||
|
||||
type clientContext struct {
|
||||
type ClientContext struct {
|
||||
Client Client // a raw neo-go client OR a local chain implementation
|
||||
CommitteeAct *actor.Actor // committee actor with the Global witness scope
|
||||
ReadOnlyInvoker *invoker.Invoker // R/O contract invoker, does not contain any signer
|
||||
SentTxs []hashVUBPair
|
||||
SentTxs []HashVUBPair
|
||||
}
|
||||
|
||||
func getN3Client(v *viper.Viper) (Client, error) {
|
||||
func NewRemoteClient(v *viper.Viper) (Client, error) {
|
||||
// number of opened connections
|
||||
// by neo-go client per one host
|
||||
const (
|
||||
|
@ -55,13 +51,27 @@ func getN3Client(v *viper.Viper) (Client, error) {
|
|||
)
|
||||
|
||||
ctx := context.Background()
|
||||
endpoint := v.GetString(endpointFlag)
|
||||
endpoint := v.GetString(commonflags.EndpointFlag)
|
||||
if endpoint == "" {
|
||||
return nil, errors.New("missing endpoint")
|
||||
}
|
||||
|
||||
var cfg *tls.Config
|
||||
if rootCAs := v.GetStringSlice("tls.trusted_ca_list"); len(rootCAs) != 0 {
|
||||
certFile := v.GetString("tls.certificate")
|
||||
keyFile := v.GetString("tls.key")
|
||||
|
||||
tlsConfig, err := rpcclient.TLSClientConfig(rootCAs, certFile, keyFile)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cfg = tlsConfig
|
||||
}
|
||||
c, err := rpcclient.New(ctx, endpoint, rpcclient.Options{
|
||||
MaxConnsPerHost: maxConnsPerHost,
|
||||
RequestTimeout: requestTimeout,
|
||||
TLSClientConfig: cfg,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
@ -72,20 +82,26 @@ func getN3Client(v *viper.Viper) (Client, error) {
|
|||
return c, nil
|
||||
}
|
||||
|
||||
func defaultClientContext(c Client, committeeAcc *wallet.Account) (*clientContext, error) {
|
||||
commAct, err := newActor(c, committeeAcc)
|
||||
func defaultClientContext(c Client, committeeAcc *wallet.Account) (*ClientContext, error) {
|
||||
commAct, err := actor.New(c, []actor.SignerAccount{{
|
||||
Signer: transaction.Signer{
|
||||
Account: committeeAcc.Contract.ScriptHash(),
|
||||
Scopes: transaction.Global,
|
||||
},
|
||||
Account: committeeAcc,
|
||||
}})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &clientContext{
|
||||
return &ClientContext{
|
||||
Client: c,
|
||||
CommitteeAct: commAct,
|
||||
ReadOnlyInvoker: invoker.New(c, nil),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c *clientContext) sendTx(tx *transaction.Transaction, cmd *cobra.Command, await bool) error {
|
||||
func (c *ClientContext) SendTx(tx *transaction.Transaction, cmd *cobra.Command, await bool) error {
|
||||
h, err := c.Client.SendRawTransaction(tx)
|
||||
if err != nil {
|
||||
return err
|
||||
|
@ -95,10 +111,27 @@ func (c *clientContext) sendTx(tx *transaction.Transaction, cmd *cobra.Command,
|
|||
return fmt.Errorf("sent and actual tx hashes mismatch:\n\tsent: %v\n\tactual: %v", tx.Hash().StringLE(), h.StringLE())
|
||||
}
|
||||
|
||||
c.SentTxs = append(c.SentTxs, hashVUBPair{hash: h, vub: tx.ValidUntilBlock})
|
||||
c.SentTxs = append(c.SentTxs, HashVUBPair{Hash: h, Vub: tx.ValidUntilBlock})
|
||||
|
||||
if await {
|
||||
return c.awaitTx(cmd)
|
||||
return c.AwaitTx(cmd)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *ClientContext) AwaitTx(cmd *cobra.Command) error {
|
||||
if len(c.SentTxs) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
if local, ok := c.Client.(*LocalClient); ok {
|
||||
if err := local.putTransactions(); err != nil {
|
||||
return fmt.Errorf("can't persist transactions: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
err := AwaitTx(cmd, c.Client, c.SentTxs)
|
||||
c.SentTxs = c.SentTxs[:0]
|
||||
|
||||
return err
|
||||
}
|
129
cmd/frostfs-adm/internal/modules/morph/helper/netmap.go
Normal file
129
cmd/frostfs-adm/internal/modules/morph/helper/netmap.go
Normal file
|
@ -0,0 +1,129 @@
|
|||
package helper
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/constants"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/morph/client/netmap"
|
||||
"github.com/nspcc-dev/neo-go/pkg/io"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/invoker"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/management"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/unwrap"
|
||||
"github.com/nspcc-dev/neo-go/pkg/smartcontract/callflag"
|
||||
"github.com/nspcc-dev/neo-go/pkg/util"
|
||||
"github.com/nspcc-dev/neo-go/pkg/vm/emit"
|
||||
"github.com/nspcc-dev/neo-go/pkg/vm/stackitem"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var NetmapConfigKeys = []string{
|
||||
netmap.EpochDurationConfig,
|
||||
netmap.MaxObjectSizeConfig,
|
||||
netmap.ContainerFeeConfig,
|
||||
netmap.ContainerAliasFeeConfig,
|
||||
netmap.IrCandidateFeeConfig,
|
||||
netmap.WithdrawFeeConfig,
|
||||
netmap.HomomorphicHashingDisabledKey,
|
||||
netmap.MaintenanceModeAllowedConfig,
|
||||
}
|
||||
|
||||
var errFailedToFetchListOfNetworkKeys = errors.New("can't fetch list of network config keys from the netmap contract")
|
||||
|
||||
func GetDefaultNetmapContractConfigMap() map[string]any {
|
||||
m := make(map[string]any)
|
||||
m[netmap.EpochDurationConfig] = viper.GetInt64(commonflags.EpochDurationInitFlag)
|
||||
m[netmap.MaxObjectSizeConfig] = viper.GetInt64(commonflags.MaxObjectSizeInitFlag)
|
||||
m[netmap.MaxECDataCountConfig] = viper.GetInt64(commonflags.MaxECDataCountFlag)
|
||||
m[netmap.MaxECParityCountConfig] = viper.GetInt64(commonflags.MaxECParityCounFlag)
|
||||
m[netmap.ContainerFeeConfig] = viper.GetInt64(commonflags.ContainerFeeInitFlag)
|
||||
m[netmap.ContainerAliasFeeConfig] = viper.GetInt64(commonflags.ContainerAliasFeeInitFlag)
|
||||
m[netmap.IrCandidateFeeConfig] = viper.GetInt64(commonflags.CandidateFeeInitFlag)
|
||||
m[netmap.WithdrawFeeConfig] = viper.GetInt64(commonflags.WithdrawFeeInitFlag)
|
||||
m[netmap.HomomorphicHashingDisabledKey] = viper.GetBool(commonflags.HomomorphicHashDisabledInitFlag)
|
||||
m[netmap.MaintenanceModeAllowedConfig] = viper.GetBool(commonflags.MaintenanceModeAllowedInitFlag)
|
||||
return m
|
||||
}
|
||||
|
||||
func ParseConfigFromNetmapContract(arr []stackitem.Item) (map[string][]byte, error) {
|
||||
m := make(map[string][]byte, len(arr))
|
||||
for _, param := range arr {
|
||||
tuple, ok := param.Value().([]stackitem.Item)
|
||||
if !ok || len(tuple) != 2 {
|
||||
return nil, errors.New("invalid ListConfig response from netmap contract")
|
||||
}
|
||||
|
||||
k, err := tuple[0].TryBytes()
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid config key from netmap contract")
|
||||
}
|
||||
|
||||
v, err := tuple[1].TryBytes()
|
||||
if err != nil {
|
||||
return nil, InvalidConfigValueErr(string(k))
|
||||
}
|
||||
m[string(k)] = v
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func InvalidConfigValueErr(key string) error {
|
||||
return fmt.Errorf("invalid %s config value from netmap contract", key)
|
||||
}
|
||||
|
||||
func EmitNewEpochCall(bw *io.BufBinWriter, wCtx *InitializeContext, nmHash util.Uint160, countEpoch int64) error {
|
||||
if countEpoch <= 0 {
|
||||
return errors.New("number of epochs cannot be less than 1")
|
||||
}
|
||||
|
||||
curr, err := unwrap.Int64(wCtx.ReadOnlyInvoker.Call(nmHash, "epoch"))
|
||||
if err != nil {
|
||||
return errors.New("can't fetch current epoch from the netmap contract")
|
||||
}
|
||||
|
||||
newEpoch := curr + countEpoch
|
||||
wCtx.Command.Printf("Current epoch: %d, increase to %d.\n", curr, newEpoch)
|
||||
|
||||
// In NeoFS this is done via Notary contract. Here, however, we can form the
|
||||
// transaction locally.
|
||||
emit.AppCall(bw.BinWriter, nmHash, "newEpoch", callflag.All, newEpoch)
|
||||
return bw.Err
|
||||
}
|
||||
|
||||
func GetNetConfigFromNetmapContract(roInvoker *invoker.Invoker) ([]stackitem.Item, error) {
|
||||
r := management.NewReader(roInvoker)
|
||||
cs, err := GetContractByID(r, 1)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get nns contract: %w", err)
|
||||
}
|
||||
nmHash, err := NNSResolveHash(roInvoker, cs.Hash, DomainOf(constants.NetmapContract))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't get netmap contract hash: %w", err)
|
||||
}
|
||||
arr, err := unwrap.Array(roInvoker.Call(nmHash, "listConfig"))
|
||||
if err != nil {
|
||||
return nil, errFailedToFetchListOfNetworkKeys
|
||||
}
|
||||
return arr, err
|
||||
}
|
||||
|
||||
func MergeNetmapConfig(roInvoker *invoker.Invoker, md map[string]any) error {
|
||||
arr, err := GetNetConfigFromNetmapContract(roInvoker)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
m, err := ParseConfigFromNetmapContract(arr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for k, v := range m {
|
||||
for _, key := range NetmapConfigKeys {
|
||||
if k == key {
|
||||
md[k] = v
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
188
cmd/frostfs-adm/internal/modules/morph/helper/util.go
Normal file
188
cmd/frostfs-adm/internal/modules/morph/helper/util.go
Normal file
|
@ -0,0 +1,188 @@
|
|||
package helper
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"compress/gzip"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/config"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/constants"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/innerring"
|
||||
"github.com/nspcc-dev/neo-go/pkg/core/state"
|
||||
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
|
||||
"github.com/nspcc-dev/neo-go/pkg/encoding/fixedn"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/management"
|
||||
"github.com/nspcc-dev/neo-go/pkg/wallet"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
func GetAlphabetWallets(v *viper.Viper, walletDir string) ([]*wallet.Wallet, error) {
|
||||
wallets, err := openAlphabetWallets(v, walletDir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(wallets) > constants.MaxAlphabetNodes {
|
||||
return nil, ErrTooManyAlphabetNodes
|
||||
}
|
||||
return wallets, nil
|
||||
}
|
||||
|
||||
func openAlphabetWallets(v *viper.Viper, walletDir string) ([]*wallet.Wallet, error) {
|
||||
walletFiles, err := os.ReadDir(walletDir)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't read alphabet wallets dir: %w", err)
|
||||
}
|
||||
|
||||
var wallets []*wallet.Wallet
|
||||
var letter string
|
||||
for i := range constants.MaxAlphabetNodes {
|
||||
letter = innerring.GlagoliticLetter(i).String()
|
||||
p := filepath.Join(walletDir, letter+".json")
|
||||
var w *wallet.Wallet
|
||||
w, err = wallet.NewWalletFromFile(p)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
err = nil
|
||||
} else {
|
||||
err = fmt.Errorf("can't open wallet: %w", err)
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
var password string
|
||||
password, err = config.GetPassword(v, letter)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("can't fetch password: %w", err)
|
||||
break
|
||||
}
|
||||
|
||||
for i := range w.Accounts {
|
||||
if err = w.Accounts[i].Decrypt(password, keys.NEP2ScryptParams()); err != nil {
|
||||
err = fmt.Errorf("can't unlock wallet: %w", err)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
wallets = append(wallets, w)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't read wallet for letter '%s': %w", letter, err)
|
||||
}
|
||||
if len(wallets) == 0 {
|
||||
err = errors.New("there are no alphabet wallets in dir (run `generate-alphabet` command first)")
|
||||
if len(walletFiles) > 0 {
|
||||
err = fmt.Errorf("use glagolitic names for wallets(run `print-alphabet`): %w", err)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return wallets, nil
|
||||
}
|
||||
|
||||
func ReadContract(ctrPath, ctrName string) (*ContractState, error) {
|
||||
rawNef, err := os.ReadFile(filepath.Join(ctrPath, ctrName+"_contract.nef"))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't read NEF file for %s contract: %w", ctrName, err)
|
||||
}
|
||||
rawManif, err := os.ReadFile(filepath.Join(ctrPath, "config.json"))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't read manifest file for %s contract: %w", ctrName, err)
|
||||
}
|
||||
|
||||
cs := &ContractState{
|
||||
RawNEF: rawNef,
|
||||
RawManifest: rawManif,
|
||||
}
|
||||
|
||||
return cs, cs.Parse()
|
||||
}
|
||||
|
||||
func readContractsFromArchive(file io.Reader, names []string) (map[string]*ContractState, error) {
|
||||
m := make(map[string]*ContractState, len(names))
|
||||
for i := range names {
|
||||
m[names[i]] = new(ContractState)
|
||||
}
|
||||
|
||||
gr, err := gzip.NewReader(file)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("contracts file must be tar.gz archive: %w", err)
|
||||
}
|
||||
|
||||
r := tar.NewReader(gr)
|
||||
var h *tar.Header
|
||||
for h, err = r.Next(); err == nil && h != nil; h, err = r.Next() {
|
||||
if h.Typeflag != tar.TypeReg {
|
||||
continue
|
||||
}
|
||||
dir, _ := filepath.Split(h.Name)
|
||||
ctrName := filepath.Base(dir)
|
||||
|
||||
cs, ok := m[ctrName]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
switch {
|
||||
case strings.HasSuffix(h.Name, filepath.Join(ctrName, ctrName+"_contract.nef")):
|
||||
cs.RawNEF, err = io.ReadAll(r)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't read NEF file for %s contract: %w", ctrName, err)
|
||||
}
|
||||
case strings.HasSuffix(h.Name, "config.json"):
|
||||
cs.RawManifest, err = io.ReadAll(r)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't read manifest file for %s contract: %w", ctrName, err)
|
||||
}
|
||||
}
|
||||
m[ctrName] = cs
|
||||
}
|
||||
if err != nil && err != io.EOF {
|
||||
return nil, fmt.Errorf("can't read contracts from archive: %w", err)
|
||||
}
|
||||
|
||||
for ctrName, cs := range m {
|
||||
if cs.RawNEF == nil {
|
||||
return nil, fmt.Errorf("NEF for %s contract wasn't found", ctrName)
|
||||
}
|
||||
if cs.RawManifest == nil {
|
||||
return nil, fmt.Errorf("manifest for %s contract wasn't found", ctrName)
|
||||
}
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func GetAlphabetNNSDomain(i int) string {
|
||||
return constants.AlphabetContract + strconv.FormatUint(uint64(i), 10) + ".frostfs"
|
||||
}
|
||||
|
||||
func ParseGASAmount(s string) (fixedn.Fixed8, error) {
|
||||
gasAmount, err := fixedn.Fixed8FromString(s)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("invalid GAS amount %s: %w", s, err)
|
||||
}
|
||||
if gasAmount <= 0 {
|
||||
return 0, fmt.Errorf("GAS amount must be positive (got %d)", gasAmount)
|
||||
}
|
||||
return gasAmount, nil
|
||||
}
|
||||
|
||||
// GetContractByID retrieves a contract by its ID using the standard GetContractByID method.
|
||||
// However, if the returned state.Contract is nil, it returns an error indicating that the contract was not found.
|
||||
// See https://git.frostfs.info/TrueCloudLab/frostfs-node/issues/1210
|
||||
func GetContractByID(r *management.ContractReader, id int32) (*state.Contract, error) {
|
||||
cs, err := r.GetContractByID(id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if cs == nil {
|
||||
return nil, errors.New("contract not found")
|
||||
}
|
||||
return cs, nil
|
||||
}
|
76
cmd/frostfs-adm/internal/modules/morph/helper/wallet.go
Normal file
76
cmd/frostfs-adm/internal/modules/morph/helper/wallet.go
Normal file
|
@ -0,0 +1,76 @@
|
|||
package helper
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/config"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/constants"
|
||||
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
|
||||
"github.com/nspcc-dev/neo-go/pkg/wallet"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
func InitializeContractWallet(v *viper.Viper, walletDir string) (*wallet.Wallet, error) {
|
||||
password, err := config.GetPassword(v, constants.ContractWalletPasswordKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
w, err := wallet.NewWallet(filepath.Join(walletDir, constants.ContractWalletFilename))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
acc, err := wallet.NewAccount()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
err = acc.Encrypt(password, keys.NEP2ScryptParams())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
w.AddAccount(acc)
|
||||
if err := w.SavePretty(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return w, nil
|
||||
}
|
||||
|
||||
func openContractWallet(v *viper.Viper, cmd *cobra.Command, walletDir string) (*wallet.Wallet, error) {
|
||||
p := filepath.Join(walletDir, constants.ContractWalletFilename)
|
||||
w, err := wallet.NewWalletFromFile(p)
|
||||
if err != nil {
|
||||
if !os.IsNotExist(err) {
|
||||
return nil, fmt.Errorf("can't open wallet: %w", err)
|
||||
}
|
||||
|
||||
cmd.Printf("Contract group wallet is missing, initialize at %s\n", p)
|
||||
return InitializeContractWallet(v, walletDir)
|
||||
}
|
||||
|
||||
password, err := config.GetPassword(v, constants.ContractWalletPasswordKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for i := range w.Accounts {
|
||||
if err := w.Accounts[i].Decrypt(password, keys.NEP2ScryptParams()); err != nil {
|
||||
return nil, fmt.Errorf("can't unlock wallet: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return w, nil
|
||||
}
|
||||
|
||||
func getWallet(cmd *cobra.Command, v *viper.Viper, needContracts bool, walletDir string) (*wallet.Wallet, error) {
|
||||
if !needContracts {
|
||||
return nil, nil
|
||||
}
|
||||
return openContractWallet(v, cmd, walletDir)
|
||||
}
|
|
@ -1,476 +0,0 @@
|
|||
package morph
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/config"
|
||||
morphClient "git.frostfs.info/TrueCloudLab/frostfs-node/pkg/morph/client"
|
||||
"github.com/nspcc-dev/neo-go/pkg/core/native/nativenames"
|
||||
"github.com/nspcc-dev/neo-go/pkg/core/state"
|
||||
"github.com/nspcc-dev/neo-go/pkg/core/transaction"
|
||||
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/actor"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/management"
|
||||
"github.com/nspcc-dev/neo-go/pkg/smartcontract/trigger"
|
||||
"github.com/nspcc-dev/neo-go/pkg/util"
|
||||
"github.com/nspcc-dev/neo-go/pkg/vm/vmstate"
|
||||
"github.com/nspcc-dev/neo-go/pkg/wallet"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
const (
|
||||
// maxAlphabetNodes is the maximum number of candidates allowed, which is currently limited by the size
|
||||
// of the invocation script.
|
||||
// See: https://github.com/nspcc-dev/neo-go/blob/740488f7f35e367eaa99a71c0a609c315fe2b0fc/pkg/core/transaction/witness.go#L10
|
||||
maxAlphabetNodes = 22
|
||||
)
|
||||
|
||||
type cache struct {
|
||||
nnsCs *state.Contract
|
||||
groupKey *keys.PublicKey
|
||||
}
|
||||
|
||||
type initializeContext struct {
|
||||
clientContext
|
||||
cache
|
||||
// CommitteeAcc is used for retrieving the committee address and the verification script.
|
||||
CommitteeAcc *wallet.Account
|
||||
// ConsensusAcc is used for retrieving the committee address and the verification script.
|
||||
ConsensusAcc *wallet.Account
|
||||
Wallets []*wallet.Wallet
|
||||
// ContractWallet is a wallet for providing the contract group signature.
|
||||
ContractWallet *wallet.Wallet
|
||||
// Accounts contains simple signature accounts in the same order as in Wallets.
|
||||
Accounts []*wallet.Account
|
||||
Contracts map[string]*contractState
|
||||
Command *cobra.Command
|
||||
ContractPath string
|
||||
}
|
||||
|
||||
var ErrTooManyAlphabetNodes = fmt.Errorf("too many alphabet nodes (maximum allowed is %d)", maxAlphabetNodes)
|
||||
|
||||
func initializeSideChainCmd(cmd *cobra.Command, _ []string) error {
|
||||
initCtx, err := newInitializeContext(cmd, viper.GetViper())
|
||||
if err != nil {
|
||||
return fmt.Errorf("initialization error: %w", err)
|
||||
}
|
||||
defer initCtx.close()
|
||||
|
||||
// 1. Transfer funds to committee accounts.
|
||||
cmd.Println("Stage 1: transfer GAS to alphabet nodes.")
|
||||
if err := initCtx.transferFunds(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cmd.Println("Stage 2: set notary and alphabet nodes in designate contract.")
|
||||
if err := initCtx.setNotaryAndAlphabetNodes(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 3. Deploy NNS contract.
|
||||
cmd.Println("Stage 3: deploy NNS contract.")
|
||||
if err := initCtx.deployNNS(deployMethodName); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 4. Deploy NeoFS contracts.
|
||||
cmd.Println("Stage 4: deploy NeoFS contracts.")
|
||||
if err := initCtx.deployContracts(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cmd.Println("Stage 4.1: Transfer GAS to proxy contract.")
|
||||
if err := initCtx.transferGASToProxy(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cmd.Println("Stage 5: register candidates.")
|
||||
if err := initCtx.registerCandidates(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cmd.Println("Stage 6: transfer NEO to alphabet contracts.")
|
||||
if err := initCtx.transferNEOToAlphabetContracts(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cmd.Println("Stage 7: set addresses in NNS.")
|
||||
return initCtx.setNNS()
|
||||
}
|
||||
|
||||
func (c *initializeContext) close() {
|
||||
if local, ok := c.Client.(*localClient); ok {
|
||||
err := local.dump()
|
||||
if err != nil {
|
||||
c.Command.PrintErrf("Can't write dump: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func newInitializeContext(cmd *cobra.Command, v *viper.Viper) (*initializeContext, error) {
|
||||
walletDir := config.ResolveHomePath(viper.GetString(alphabetWalletsFlag))
|
||||
wallets, err := getAlphabetWallets(v, walletDir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
needContracts := cmd.Name() == "update-contracts" || cmd.Name() == "init"
|
||||
|
||||
var w *wallet.Wallet
|
||||
w, err = getWallet(cmd, v, needContracts, walletDir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
c, err := createClient(cmd, v, wallets)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
committeeAcc, err := getWalletAccount(wallets[0], committeeAccountName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't find committee account: %w", err)
|
||||
}
|
||||
|
||||
consensusAcc, err := getWalletAccount(wallets[0], consensusAccountName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't find consensus account: %w", err)
|
||||
}
|
||||
|
||||
if err := validateInit(cmd); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ctrPath, err := getContractsPath(cmd, needContracts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := checkNotaryEnabled(c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
accounts, err := createWalletAccounts(wallets)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cliCtx, err := defaultClientContext(c, committeeAcc)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("client context: %w", err)
|
||||
}
|
||||
|
||||
initCtx := &initializeContext{
|
||||
clientContext: *cliCtx,
|
||||
ConsensusAcc: consensusAcc,
|
||||
CommitteeAcc: committeeAcc,
|
||||
ContractWallet: w,
|
||||
Wallets: wallets,
|
||||
Accounts: accounts,
|
||||
Command: cmd,
|
||||
Contracts: make(map[string]*contractState),
|
||||
ContractPath: ctrPath,
|
||||
}
|
||||
|
||||
if needContracts {
|
||||
err := initCtx.readContracts(fullContractList)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return initCtx, nil
|
||||
}
|
||||
|
||||
func validateInit(cmd *cobra.Command) error {
|
||||
if cmd.Name() != "init" {
|
||||
return nil
|
||||
}
|
||||
if viper.GetInt64(epochDurationInitFlag) <= 0 {
|
||||
return fmt.Errorf("epoch duration must be positive")
|
||||
}
|
||||
|
||||
if viper.GetInt64(maxObjectSizeInitFlag) <= 0 {
|
||||
return fmt.Errorf("max object size must be positive")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func createClient(cmd *cobra.Command, v *viper.Viper, wallets []*wallet.Wallet) (Client, error) {
|
||||
var c Client
|
||||
var err error
|
||||
if ldf := cmd.Flags().Lookup(localDumpFlag); ldf != nil && ldf.Changed {
|
||||
if cmd.Flags().Changed(endpointFlag) {
|
||||
return nil, fmt.Errorf("`%s` and `%s` flags are mutually exclusive", endpointFlag, localDumpFlag)
|
||||
}
|
||||
c, err = newLocalClient(cmd, v, wallets, ldf.Value.String())
|
||||
} else {
|
||||
c, err = getN3Client(v)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't create N3 client: %w", err)
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func getWallet(cmd *cobra.Command, v *viper.Viper, needContracts bool, walletDir string) (*wallet.Wallet, error) {
|
||||
if !needContracts {
|
||||
return nil, nil
|
||||
}
|
||||
return openContractWallet(v, cmd, walletDir)
|
||||
}
|
||||
|
||||
func getContractsPath(cmd *cobra.Command, needContracts bool) (string, error) {
|
||||
if !needContracts {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
ctrPath, err := cmd.Flags().GetString(contractsInitFlag)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("invalid contracts path: %w", err)
|
||||
}
|
||||
return ctrPath, nil
|
||||
}
|
||||
|
||||
func createWalletAccounts(wallets []*wallet.Wallet) ([]*wallet.Account, error) {
|
||||
accounts := make([]*wallet.Account, len(wallets))
|
||||
for i, w := range wallets {
|
||||
acc, err := getWalletAccount(w, singleAccountName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("wallet %s is invalid (no single account): %w", w.Path(), err)
|
||||
}
|
||||
accounts[i] = acc
|
||||
}
|
||||
return accounts, nil
|
||||
}
|
||||
|
||||
func (c *initializeContext) awaitTx() error {
|
||||
return c.clientContext.awaitTx(c.Command)
|
||||
}
|
||||
|
||||
func (c *initializeContext) nnsContractState() (*state.Contract, error) {
|
||||
if c.nnsCs != nil {
|
||||
return c.nnsCs, nil
|
||||
}
|
||||
|
||||
r := management.NewReader(c.ReadOnlyInvoker)
|
||||
cs, err := r.GetContractByID(1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
c.nnsCs = cs
|
||||
return cs, nil
|
||||
}
|
||||
|
||||
func (c *initializeContext) getSigner(tryGroup bool, acc *wallet.Account) transaction.Signer {
|
||||
if tryGroup && c.groupKey != nil {
|
||||
return transaction.Signer{
|
||||
Account: acc.Contract.ScriptHash(),
|
||||
Scopes: transaction.CustomGroups,
|
||||
AllowedGroups: keys.PublicKeys{c.groupKey},
|
||||
}
|
||||
}
|
||||
|
||||
signer := transaction.Signer{
|
||||
Account: acc.Contract.ScriptHash(),
|
||||
Scopes: transaction.Global, // Scope is important, as we have nested call to container contract.
|
||||
}
|
||||
|
||||
if !tryGroup {
|
||||
return signer
|
||||
}
|
||||
|
||||
nnsCs, err := c.nnsContractState()
|
||||
if err != nil {
|
||||
return signer
|
||||
}
|
||||
|
||||
groupKey, err := nnsResolveKey(c.ReadOnlyInvoker, nnsCs.Hash, morphClient.NNSGroupKeyName)
|
||||
if err == nil {
|
||||
c.groupKey = groupKey
|
||||
|
||||
signer.Scopes = transaction.CustomGroups
|
||||
signer.AllowedGroups = keys.PublicKeys{groupKey}
|
||||
}
|
||||
return signer
|
||||
}
|
||||
|
||||
func (c *clientContext) awaitTx(cmd *cobra.Command) error {
|
||||
if len(c.SentTxs) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
if local, ok := c.Client.(*localClient); ok {
|
||||
if err := local.putTransactions(); err != nil {
|
||||
return fmt.Errorf("can't persist transactions: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
err := awaitTx(cmd, c.Client, c.SentTxs)
|
||||
c.SentTxs = c.SentTxs[:0]
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func awaitTx(cmd *cobra.Command, c Client, txs []hashVUBPair) error {
|
||||
cmd.Println("Waiting for transactions to persist...")
|
||||
|
||||
at := trigger.Application
|
||||
|
||||
var retErr error
|
||||
|
||||
loop:
|
||||
for i := range txs {
|
||||
var it int
|
||||
var pollInterval time.Duration
|
||||
var pollIntervalChanged bool
|
||||
for {
|
||||
// We must fetch current height before application log, to avoid race condition.
|
||||
currBlock, err := c.GetBlockCount()
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't fetch current block height: %w", err)
|
||||
}
|
||||
res, err := c.GetApplicationLog(txs[i].hash, &at)
|
||||
if err == nil {
|
||||
if retErr == nil && len(res.Executions) > 0 && res.Executions[0].VMState != vmstate.Halt {
|
||||
retErr = fmt.Errorf("tx %d persisted in %s state: %s",
|
||||
i, res.Executions[0].VMState, res.Executions[0].FaultException)
|
||||
}
|
||||
continue loop
|
||||
}
|
||||
if txs[i].vub < currBlock {
|
||||
return fmt.Errorf("tx was not persisted: vub=%d, height=%d", txs[i].vub, currBlock)
|
||||
}
|
||||
|
||||
pollInterval, pollIntervalChanged = nextPollInterval(it, pollInterval)
|
||||
if pollIntervalChanged && viper.GetBool(commonflags.Verbose) {
|
||||
cmd.Printf("Pool interval to check transaction persistence changed: %s\n", pollInterval.String())
|
||||
}
|
||||
|
||||
timer := time.NewTimer(pollInterval)
|
||||
select {
|
||||
case <-cmd.Context().Done():
|
||||
return cmd.Context().Err()
|
||||
case <-timer.C:
|
||||
}
|
||||
|
||||
it++
|
||||
}
|
||||
}
|
||||
|
||||
return retErr
|
||||
}
|
||||
|
||||
func nextPollInterval(it int, previous time.Duration) (time.Duration, bool) {
|
||||
const minPollInterval = 1 * time.Second
|
||||
const maxPollInterval = 16 * time.Second
|
||||
const changeAfter = 5
|
||||
if it == 0 {
|
||||
return minPollInterval, true
|
||||
}
|
||||
if it%changeAfter != 0 {
|
||||
return previous, false
|
||||
}
|
||||
nextInterval := previous * 2
|
||||
if nextInterval > maxPollInterval {
|
||||
return maxPollInterval, previous != maxPollInterval
|
||||
}
|
||||
return nextInterval, true
|
||||
}
|
||||
|
||||
// sendCommitteeTx creates transaction from script, signs it by committee nodes and sends it to RPC.
|
||||
// If tryGroup is false, global scope is used for the signer (useful when
|
||||
// working with native contracts).
|
||||
func (c *initializeContext) sendCommitteeTx(script []byte, tryGroup bool) error {
|
||||
return c.sendMultiTx(script, tryGroup, false)
|
||||
}
|
||||
|
||||
// sendConsensusTx creates transaction from script, signs it by alphabet nodes and sends it to RPC.
|
||||
// Not that because this is used only after the contracts were initialized and deployed,
|
||||
// we always try to have a group scope.
|
||||
func (c *initializeContext) sendConsensusTx(script []byte) error {
|
||||
return c.sendMultiTx(script, true, true)
|
||||
}
|
||||
|
||||
func (c *initializeContext) sendMultiTx(script []byte, tryGroup bool, withConsensus bool) error {
|
||||
var act *actor.Actor
|
||||
var err error
|
||||
|
||||
withConsensus = withConsensus && !c.ConsensusAcc.Contract.ScriptHash().Equals(c.CommitteeAcc.ScriptHash())
|
||||
if tryGroup {
|
||||
// Even for consensus signatures we need the committee to pay.
|
||||
signers := make([]actor.SignerAccount, 1, 2)
|
||||
signers[0] = actor.SignerAccount{
|
||||
Signer: c.getSigner(tryGroup, c.CommitteeAcc),
|
||||
Account: c.CommitteeAcc,
|
||||
}
|
||||
if withConsensus {
|
||||
signers = append(signers, actor.SignerAccount{
|
||||
Signer: c.getSigner(tryGroup, c.ConsensusAcc),
|
||||
Account: c.ConsensusAcc,
|
||||
})
|
||||
}
|
||||
act, err = actor.New(c.Client, signers)
|
||||
} else {
|
||||
if withConsensus {
|
||||
panic("BUG: should never happen")
|
||||
}
|
||||
act, err = c.CommitteeAct, nil
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("could not create actor: %w", err)
|
||||
}
|
||||
|
||||
tx, err := act.MakeUnsignedRun(script, []transaction.Attribute{{Type: transaction.HighPriority}})
|
||||
if err != nil {
|
||||
return fmt.Errorf("could not perform test invocation: %w", err)
|
||||
}
|
||||
|
||||
if err := c.multiSign(tx, committeeAccountName); err != nil {
|
||||
return err
|
||||
}
|
||||
if withConsensus {
|
||||
if err := c.multiSign(tx, consensusAccountName); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return c.sendTx(tx, c.Command, false)
|
||||
}
|
||||
|
||||
func getWalletAccount(w *wallet.Wallet, typ string) (*wallet.Account, error) {
|
||||
for i := range w.Accounts {
|
||||
if w.Accounts[i].Label == typ {
|
||||
return w.Accounts[i], nil
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("account for '%s' not found", typ)
|
||||
}
|
||||
|
||||
func checkNotaryEnabled(c Client) error {
|
||||
ns, err := c.GetNativeContracts()
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't get native contract hashes: %w", err)
|
||||
}
|
||||
|
||||
notaryEnabled := false
|
||||
nativeHashes := make(map[string]util.Uint160, len(ns))
|
||||
for i := range ns {
|
||||
if ns[i].Manifest.Name == nativenames.Notary {
|
||||
notaryEnabled = true
|
||||
}
|
||||
nativeHashes[ns[i].Manifest.Name] = ns[i].Hash
|
||||
}
|
||||
if !notaryEnabled {
|
||||
return errors.New("notary contract must be enabled")
|
||||
}
|
||||
return nil
|
||||
}
|
|
@ -0,0 +1,59 @@
|
|||
package initialize
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/constants"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/helper"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
func initializeSideChainCmd(cmd *cobra.Command, _ []string) error {
|
||||
initCtx, err := helper.NewInitializeContext(cmd, viper.GetViper())
|
||||
if err != nil {
|
||||
return fmt.Errorf("initialization error: %w", err)
|
||||
}
|
||||
defer initCtx.Close()
|
||||
|
||||
// 1. Transfer funds to committee accounts.
|
||||
cmd.Println("Stage 1: transfer GAS to alphabet nodes.")
|
||||
if err := transferFunds(initCtx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cmd.Println("Stage 2: set notary and alphabet nodes in designate contract.")
|
||||
if err := setNotaryAndAlphabetNodes(initCtx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 3. Deploy NNS contract.
|
||||
cmd.Println("Stage 3: deploy NNS contract.")
|
||||
if err := helper.DeployNNS(initCtx, constants.DeployMethodName); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 4. Deploy NeoFS contracts.
|
||||
cmd.Println("Stage 4: deploy NeoFS contracts.")
|
||||
if err := deployContracts(initCtx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cmd.Println("Stage 4.1: Transfer GAS to proxy contract.")
|
||||
if err := transferGASToProxy(initCtx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cmd.Println("Stage 5: register candidates.")
|
||||
if err := registerCandidates(initCtx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cmd.Println("Stage 6: transfer NEO to alphabet contracts.")
|
||||
if err := transferNEOToAlphabetContracts(initCtx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cmd.Println("Stage 7: set addresses in NNS.")
|
||||
return setNNS(initCtx)
|
||||
}
|
|
@ -0,0 +1,80 @@
|
|||
package initialize
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/constants"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/helper"
|
||||
"github.com/nspcc-dev/neo-go/pkg/core/state"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/actor"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/management"
|
||||
)
|
||||
|
||||
func deployContracts(c *helper.InitializeContext) error {
|
||||
alphaCs := c.GetContract(constants.AlphabetContract)
|
||||
|
||||
var keysParam []any
|
||||
|
||||
baseGroups := alphaCs.Manifest.Groups
|
||||
|
||||
// alphabet contracts should be deployed by individual nodes to get different hashes.
|
||||
for i, acc := range c.Accounts {
|
||||
ctrHash := state.CreateContractHash(acc.Contract.ScriptHash(), alphaCs.NEF.Checksum, alphaCs.Manifest.Name)
|
||||
if c.IsUpdated(ctrHash, alphaCs) {
|
||||
c.Command.Printf("Alphabet contract #%d is already deployed.\n", i)
|
||||
continue
|
||||
}
|
||||
|
||||
alphaCs.Manifest.Groups = baseGroups
|
||||
err := helper.AddManifestGroup(c.ContractWallet, ctrHash, alphaCs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't sign manifest group: %v", err)
|
||||
}
|
||||
|
||||
keysParam = append(keysParam, acc.PrivateKey().PublicKey().Bytes())
|
||||
params := helper.GetContractDeployParameters(alphaCs, c.GetAlphabetDeployItems(i, len(c.Wallets)))
|
||||
|
||||
act, err := actor.NewSimple(c.Client, acc)
|
||||
if err != nil {
|
||||
return fmt.Errorf("could not create actor: %w", err)
|
||||
}
|
||||
|
||||
txHash, vub, err := act.SendCall(management.Hash, constants.DeployMethodName, params...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't deploy alphabet #%d contract: %w", i, err)
|
||||
}
|
||||
|
||||
c.SentTxs = append(c.SentTxs, helper.HashVUBPair{Hash: txHash, Vub: vub})
|
||||
}
|
||||
|
||||
for _, ctrName := range constants.ContractList {
|
||||
cs := c.GetContract(ctrName)
|
||||
|
||||
ctrHash := cs.Hash
|
||||
if c.IsUpdated(ctrHash, cs) {
|
||||
c.Command.Printf("%s contract is already deployed.\n", ctrName)
|
||||
continue
|
||||
}
|
||||
|
||||
err := helper.AddManifestGroup(c.ContractWallet, ctrHash, cs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't sign manifest group: %v", err)
|
||||
}
|
||||
|
||||
args, err := helper.GetContractDeployData(c, ctrName, keysParam, constants.DeployMethodName)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s: getting deploy params: %v", ctrName, err)
|
||||
}
|
||||
params := helper.GetContractDeployParameters(cs, args)
|
||||
res, err := c.CommitteeAct.MakeCall(management.Hash, constants.DeployMethodName, params...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't deploy %s contract: %w", ctrName, err)
|
||||
}
|
||||
|
||||
if err := c.SendCommitteeTx(res.Script, false); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return c.AwaitTx()
|
||||
}
|
|
@ -0,0 +1,135 @@
|
|||
package initialize
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-contract/nns"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/constants"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/helper"
|
||||
morphClient "git.frostfs.info/TrueCloudLab/frostfs-node/pkg/morph/client"
|
||||
"github.com/nspcc-dev/neo-go/pkg/core/state"
|
||||
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
|
||||
"github.com/nspcc-dev/neo-go/pkg/encoding/address"
|
||||
"github.com/nspcc-dev/neo-go/pkg/io"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/management"
|
||||
"github.com/nspcc-dev/neo-go/pkg/smartcontract/callflag"
|
||||
"github.com/nspcc-dev/neo-go/pkg/util"
|
||||
"github.com/nspcc-dev/neo-go/pkg/vm/emit"
|
||||
"github.com/nspcc-dev/neo-go/pkg/vm/opcode"
|
||||
)
|
||||
|
||||
func setNNS(c *helper.InitializeContext) error {
|
||||
r := management.NewReader(c.ReadOnlyInvoker)
|
||||
nnsCs, err := helper.GetContractByID(r, 1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ok, err := c.NNSRootRegistered(nnsCs.Hash, "frostfs")
|
||||
if err != nil {
|
||||
return err
|
||||
} else if !ok {
|
||||
bw := io.NewBufBinWriter()
|
||||
emit.AppCall(bw.BinWriter, nnsCs.Hash, "register", callflag.All,
|
||||
"frostfs", c.CommitteeAcc.Contract.ScriptHash(),
|
||||
constants.FrostfsOpsEmail, constants.NNSRefreshDefVal, constants.NNSRetryDefVal,
|
||||
int64(constants.DefaultExpirationTime), constants.NNSTtlDefVal)
|
||||
emit.Opcodes(bw.BinWriter, opcode.ASSERT)
|
||||
if err := c.SendCommitteeTx(bw.Bytes(), true); err != nil {
|
||||
return fmt.Errorf("can't add domain root to NNS: %w", err)
|
||||
}
|
||||
if err := c.AwaitTx(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
alphaCs := c.GetContract(constants.AlphabetContract)
|
||||
for i, acc := range c.Accounts {
|
||||
alphaCs.Hash = state.CreateContractHash(acc.Contract.ScriptHash(), alphaCs.NEF.Checksum, alphaCs.Manifest.Name)
|
||||
|
||||
domain := helper.GetAlphabetNNSDomain(i)
|
||||
if err := nnsRegisterDomain(c, nnsCs.Hash, alphaCs.Hash, domain); err != nil {
|
||||
return err
|
||||
}
|
||||
c.Command.Printf("NNS: Set %s -> %s\n", domain, alphaCs.Hash.StringLE())
|
||||
}
|
||||
|
||||
for _, ctrName := range constants.ContractList {
|
||||
cs := c.GetContract(ctrName)
|
||||
|
||||
domain := ctrName + ".frostfs"
|
||||
if err := nnsRegisterDomain(c, nnsCs.Hash, cs.Hash, domain); err != nil {
|
||||
return err
|
||||
}
|
||||
c.Command.Printf("NNS: Set %s -> %s\n", domain, cs.Hash.StringLE())
|
||||
}
|
||||
|
||||
groupKey := c.ContractWallet.Accounts[0].PrivateKey().PublicKey()
|
||||
err = updateNNSGroup(c, nnsCs.Hash, groupKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.Command.Printf("NNS: Set %s -> %s\n", morphClient.NNSGroupKeyName, hex.EncodeToString(groupKey.Bytes()))
|
||||
|
||||
return c.AwaitTx()
|
||||
}
|
||||
|
||||
func updateNNSGroup(c *helper.InitializeContext, nnsHash util.Uint160, pub *keys.PublicKey) error {
|
||||
bw := io.NewBufBinWriter()
|
||||
keyAlreadyAdded, domainRegCodeEmitted, err := c.EmitUpdateNNSGroupScript(bw, nnsHash, pub)
|
||||
if keyAlreadyAdded || err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
script := bw.Bytes()
|
||||
if domainRegCodeEmitted {
|
||||
w := io.NewBufBinWriter()
|
||||
emit.Instruction(w.BinWriter, opcode.INITSSLOT, []byte{1})
|
||||
wrapRegisterScriptWithPrice(w, nnsHash, script)
|
||||
script = w.Bytes()
|
||||
}
|
||||
|
||||
return c.SendCommitteeTx(script, true)
|
||||
}
|
||||
|
||||
// wrapRegisterScriptWithPrice wraps a given script with `getPrice`/`setPrice` calls for NNS.
|
||||
// It is intended to be used for a single transaction, and not as a part of other scripts.
|
||||
// It is assumed that script already contains static slot initialization code, the first one
|
||||
// (with index 0) is used to store the price.
|
||||
func wrapRegisterScriptWithPrice(w *io.BufBinWriter, nnsHash util.Uint160, s []byte) {
|
||||
if len(s) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
emit.AppCall(w.BinWriter, nnsHash, "getPrice", callflag.All)
|
||||
emit.Opcodes(w.BinWriter, opcode.STSFLD0)
|
||||
emit.AppCall(w.BinWriter, nnsHash, "setPrice", callflag.All, 1)
|
||||
|
||||
w.WriteBytes(s)
|
||||
|
||||
emit.Opcodes(w.BinWriter, opcode.LDSFLD0, opcode.PUSH1, opcode.PACK)
|
||||
emit.AppCallNoArgs(w.BinWriter, nnsHash, "setPrice", callflag.All)
|
||||
|
||||
if w.Err != nil {
|
||||
panic(fmt.Errorf("BUG: can't wrap register script: %w", w.Err))
|
||||
}
|
||||
}
|
||||
|
||||
func nnsRegisterDomain(c *helper.InitializeContext, nnsHash, expectedHash util.Uint160, domain string) error {
|
||||
script, ok, err := c.NNSRegisterDomainScript(nnsHash, expectedHash, domain)
|
||||
if ok || err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
w := io.NewBufBinWriter()
|
||||
emit.Instruction(w.BinWriter, opcode.INITSSLOT, []byte{1})
|
||||
wrapRegisterScriptWithPrice(w, nnsHash, script)
|
||||
|
||||
emit.AppCall(w.BinWriter, nnsHash, "deleteRecords", callflag.All, domain, int64(nns.TXT))
|
||||
emit.AppCall(w.BinWriter, nnsHash, "addRecord", callflag.All,
|
||||
domain, int64(nns.TXT), expectedHash.StringLE())
|
||||
emit.AppCall(w.BinWriter, nnsHash, "addRecord", callflag.All,
|
||||
domain, int64(nns.TXT), address.Uint160ToString(expectedHash))
|
||||
return c.SendCommitteeTx(w.Bytes(), true)
|
||||
}
|
|
@ -1,10 +1,12 @@
|
|||
package morph
|
||||
package initialize
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/big"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/constants"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/helper"
|
||||
"github.com/nspcc-dev/neo-go/pkg/core/native"
|
||||
"github.com/nspcc-dev/neo-go/pkg/core/state"
|
||||
"github.com/nspcc-dev/neo-go/pkg/core/transaction"
|
||||
|
@ -27,8 +29,8 @@ const (
|
|||
registerBatchSize = transaction.MaxAttributes - 1
|
||||
)
|
||||
|
||||
func (c *initializeContext) registerCandidateRange(start, end int) error {
|
||||
regPrice, err := c.getCandidateRegisterPrice()
|
||||
func registerCandidateRange(c *helper.InitializeContext, start, end int) error {
|
||||
regPrice, err := getCandidateRegisterPrice(c)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't fetch registration price: %w", err)
|
||||
}
|
||||
|
@ -45,7 +47,7 @@ func (c *initializeContext) registerCandidateRange(start, end int) error {
|
|||
}
|
||||
|
||||
signers := []actor.SignerAccount{{
|
||||
Signer: c.getSigner(false, c.CommitteeAcc),
|
||||
Signer: c.GetSigner(false, c.CommitteeAcc),
|
||||
Account: c.CommitteeAcc,
|
||||
}}
|
||||
for _, acc := range c.Accounts[start:end] {
|
||||
|
@ -67,7 +69,7 @@ func (c *initializeContext) registerCandidateRange(start, end int) error {
|
|||
if err != nil {
|
||||
return fmt.Errorf("can't create tx: %w", err)
|
||||
}
|
||||
if err := c.multiSign(tx, committeeAccountName); err != nil {
|
||||
if err := c.MultiSign(tx, constants.CommitteeAccountName); err != nil {
|
||||
return fmt.Errorf("can't sign a transaction: %w", err)
|
||||
}
|
||||
|
||||
|
@ -78,10 +80,10 @@ func (c *initializeContext) registerCandidateRange(start, end int) error {
|
|||
}
|
||||
}
|
||||
|
||||
return c.sendTx(tx, c.Command, true)
|
||||
return c.SendTx(tx, c.Command, true)
|
||||
}
|
||||
|
||||
func (c *initializeContext) registerCandidates() error {
|
||||
func registerCandidates(c *helper.InitializeContext) error {
|
||||
cc, err := unwrap.Array(c.ReadOnlyInvoker.Call(neo.Hash, "getCandidates"))
|
||||
if err != nil {
|
||||
return fmt.Errorf("`getCandidates`: %w", err)
|
||||
|
@ -98,15 +100,12 @@ func (c *initializeContext) registerCandidates() error {
|
|||
// Register candidates in batches in order to overcome the signers amount limit.
|
||||
// See: https://github.com/nspcc-dev/neo-go/blob/master/pkg/core/transaction/transaction.go#L27
|
||||
for i := 0; i < need; i += registerBatchSize {
|
||||
start, end := i, i+registerBatchSize
|
||||
if end > need {
|
||||
end = need
|
||||
}
|
||||
start, end := i, min(i+registerBatchSize, need)
|
||||
// This check is sound because transactions are accepted/rejected atomically.
|
||||
if have >= end {
|
||||
continue
|
||||
}
|
||||
if err := c.registerCandidateRange(start, end); err != nil {
|
||||
if err := registerCandidateRange(c, start, end); err != nil {
|
||||
return fmt.Errorf("registering candidates %d..%d: %q", start, end-1, err)
|
||||
}
|
||||
}
|
||||
|
@ -114,15 +113,15 @@ func (c *initializeContext) registerCandidates() error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func (c *initializeContext) transferNEOToAlphabetContracts() error {
|
||||
func transferNEOToAlphabetContracts(c *helper.InitializeContext) error {
|
||||
neoHash := neo.Hash
|
||||
|
||||
ok, err := c.transferNEOFinished(neoHash)
|
||||
ok, err := transferNEOFinished(c, neoHash)
|
||||
if ok || err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cs := c.getContract(alphabetContract)
|
||||
cs := c.GetContract(constants.AlphabetContract)
|
||||
amount := initialAlphabetNEOAmount / len(c.Wallets)
|
||||
|
||||
bw := io.NewBufBinWriter()
|
||||
|
@ -133,14 +132,14 @@ func (c *initializeContext) transferNEOToAlphabetContracts() error {
|
|||
emit.Opcodes(bw.BinWriter, opcode.ASSERT)
|
||||
}
|
||||
|
||||
if err := c.sendCommitteeTx(bw.Bytes(), false); err != nil {
|
||||
if err := c.SendCommitteeTx(bw.Bytes(), false); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.awaitTx()
|
||||
return c.AwaitTx()
|
||||
}
|
||||
|
||||
func (c *initializeContext) transferNEOFinished(neoHash util.Uint160) (bool, error) {
|
||||
func transferNEOFinished(c *helper.InitializeContext, neoHash util.Uint160) (bool, error) {
|
||||
r := nep17.NewReader(c.ReadOnlyInvoker, neoHash)
|
||||
bal, err := r.BalanceOf(c.CommitteeAcc.Contract.ScriptHash())
|
||||
return bal.Cmp(big.NewInt(native.NEOTotalSupply)) == -1, err
|
||||
|
@ -148,7 +147,7 @@ func (c *initializeContext) transferNEOFinished(neoHash util.Uint160) (bool, err
|
|||
|
||||
var errGetPriceInvalid = errors.New("`getRegisterPrice`: invalid response")
|
||||
|
||||
func (c *initializeContext) getCandidateRegisterPrice() (int64, error) {
|
||||
func getCandidateRegisterPrice(c *helper.InitializeContext) (int64, error) {
|
||||
switch c.Client.(type) {
|
||||
case *rpcclient.Client:
|
||||
inv := invoker.New(c.Client, nil)
|
||||
|
@ -156,7 +155,7 @@ func (c *initializeContext) getCandidateRegisterPrice() (int64, error) {
|
|||
return reader.GetRegisterPrice()
|
||||
default:
|
||||
neoHash := neo.Hash
|
||||
res, err := invokeFunction(c.Client, neoHash, "getRegisterPrice", nil, nil)
|
||||
res, err := helper.InvokeFunction(c.Client, neoHash, "getRegisterPrice", nil, nil)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
|
@ -1,6 +1,9 @@
|
|||
package morph
|
||||
package initialize
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/helper"
|
||||
"github.com/nspcc-dev/neo-go/pkg/core/native/noderoles"
|
||||
"github.com/nspcc-dev/neo-go/pkg/io"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/rolemgmt"
|
||||
|
@ -8,8 +11,8 @@ import (
|
|||
"github.com/nspcc-dev/neo-go/pkg/vm/emit"
|
||||
)
|
||||
|
||||
func (c *initializeContext) setNotaryAndAlphabetNodes() error {
|
||||
if ok, err := c.setRolesFinished(); ok || err != nil {
|
||||
func setNotaryAndAlphabetNodes(c *helper.InitializeContext) error {
|
||||
if ok, err := setRolesFinished(c); ok || err != nil {
|
||||
if err == nil {
|
||||
c.Command.Println("Stage 2: already performed.")
|
||||
}
|
||||
|
@ -27,19 +30,23 @@ func (c *initializeContext) setNotaryAndAlphabetNodes() error {
|
|||
emit.AppCall(w.BinWriter, rolemgmt.Hash, "designateAsRole",
|
||||
callflag.States|callflag.AllowNotify, int64(noderoles.NeoFSAlphabet), pubs)
|
||||
|
||||
if err := c.sendCommitteeTx(w.Bytes(), false); err != nil {
|
||||
return err
|
||||
if err := c.SendCommitteeTx(w.Bytes(), false); err != nil {
|
||||
return fmt.Errorf("send committee transaction: %w", err)
|
||||
}
|
||||
|
||||
return c.awaitTx()
|
||||
err := c.AwaitTx()
|
||||
if err != nil {
|
||||
err = fmt.Errorf("await committee transaction: %w", err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *initializeContext) setRolesFinished() (bool, error) {
|
||||
func setRolesFinished(c *helper.InitializeContext) (bool, error) {
|
||||
height, err := c.Client.GetBlockCount()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
pubs, err := getDesignatedByRole(c.ReadOnlyInvoker, rolemgmt.Hash, noderoles.NeoFSAlphabet, height)
|
||||
pubs, err := helper.GetDesignatedByRole(c.ReadOnlyInvoker, rolemgmt.Hash, noderoles.NeoFSAlphabet, height)
|
||||
return len(pubs) == len(c.Wallets), err
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
package morph
|
||||
package initialize
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
|
@ -9,6 +9,14 @@ import (
|
|||
"testing"
|
||||
"time"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
cmdConfig "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/config"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/constants"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/generate"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/helper"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/netmap"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/node"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/policy"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/innerring"
|
||||
"github.com/nspcc-dev/neo-go/pkg/config"
|
||||
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
|
||||
|
@ -42,10 +50,10 @@ func TestInitialize(t *testing.T) {
|
|||
testInitialize(t, 16)
|
||||
})
|
||||
t.Run("max nodes", func(t *testing.T) {
|
||||
testInitialize(t, maxAlphabetNodes)
|
||||
testInitialize(t, constants.MaxAlphabetNodes)
|
||||
})
|
||||
t.Run("too many nodes", func(t *testing.T) {
|
||||
require.ErrorIs(t, generateTestData(t, t.TempDir(), maxAlphabetNodes+1), ErrTooManyAlphabetNodes)
|
||||
require.ErrorIs(t, generateTestData(t.TempDir(), constants.MaxAlphabetNodes+1), helper.ErrTooManyAlphabetNodes)
|
||||
})
|
||||
}
|
||||
|
||||
|
@ -53,66 +61,66 @@ func testInitialize(t *testing.T, committeeSize int) {
|
|||
testdataDir := t.TempDir()
|
||||
v := viper.GetViper()
|
||||
|
||||
require.NoError(t, generateTestData(t, testdataDir, committeeSize))
|
||||
v.Set(protoConfigPath, filepath.Join(testdataDir, protoFileName))
|
||||
require.NoError(t, generateTestData(testdataDir, committeeSize))
|
||||
v.Set(commonflags.ProtoConfigPath, filepath.Join(testdataDir, protoFileName))
|
||||
|
||||
// Set to the path or remove the next statement to download from the network.
|
||||
require.NoError(t, initCmd.Flags().Set(contractsInitFlag, contractsPath))
|
||||
require.NoError(t, Cmd.Flags().Set(commonflags.ContractsInitFlag, contractsPath))
|
||||
|
||||
dumpPath := filepath.Join(testdataDir, "out")
|
||||
require.NoError(t, initCmd.Flags().Set(localDumpFlag, dumpPath))
|
||||
v.Set(alphabetWalletsFlag, testdataDir)
|
||||
v.Set(epochDurationInitFlag, 1)
|
||||
v.Set(maxObjectSizeInitFlag, 1024)
|
||||
require.NoError(t, Cmd.Flags().Set(commonflags.LocalDumpFlag, dumpPath))
|
||||
v.Set(commonflags.AlphabetWalletsFlag, testdataDir)
|
||||
v.Set(commonflags.EpochDurationInitFlag, 1)
|
||||
v.Set(commonflags.MaxObjectSizeInitFlag, 1024)
|
||||
|
||||
setTestCredentials(v, committeeSize)
|
||||
require.NoError(t, initializeSideChainCmd(initCmd, nil))
|
||||
require.NoError(t, initializeSideChainCmd(Cmd, nil))
|
||||
|
||||
t.Run("force-new-epoch", func(t *testing.T) {
|
||||
require.NoError(t, forceNewEpoch.Flags().Set(localDumpFlag, dumpPath))
|
||||
require.NoError(t, forceNewEpochCmd(forceNewEpoch, nil))
|
||||
require.NoError(t, netmap.ForceNewEpoch.Flags().Set(commonflags.LocalDumpFlag, dumpPath))
|
||||
require.NoError(t, netmap.ForceNewEpochCmd(netmap.ForceNewEpoch, nil))
|
||||
})
|
||||
t.Run("set-config", func(t *testing.T) {
|
||||
require.NoError(t, setConfig.Flags().Set(localDumpFlag, dumpPath))
|
||||
require.NoError(t, setConfigCmd(setConfig, []string{"MaintenanceModeAllowed=true"}))
|
||||
require.NoError(t, cmdConfig.SetCmd.Flags().Set(commonflags.LocalDumpFlag, dumpPath))
|
||||
require.NoError(t, cmdConfig.SetConfigCmd(cmdConfig.SetCmd, []string{"MaintenanceModeAllowed=true"}))
|
||||
})
|
||||
t.Run("set-policy", func(t *testing.T) {
|
||||
require.NoError(t, setPolicy.Flags().Set(localDumpFlag, dumpPath))
|
||||
require.NoError(t, setPolicyCmd(setPolicy, []string{"ExecFeeFactor=1"}))
|
||||
require.NoError(t, policy.Set.Flags().Set(commonflags.LocalDumpFlag, dumpPath))
|
||||
require.NoError(t, policy.SetPolicyCmd(policy.Set, []string{"ExecFeeFactor=1"}))
|
||||
})
|
||||
t.Run("remove-node", func(t *testing.T) {
|
||||
pk, err := keys.NewPrivateKey()
|
||||
require.NoError(t, err)
|
||||
|
||||
pub := hex.EncodeToString(pk.PublicKey().Bytes())
|
||||
require.NoError(t, removeNodes.Flags().Set(localDumpFlag, dumpPath))
|
||||
require.NoError(t, removeNodesCmd(removeNodes, []string{pub}))
|
||||
require.NoError(t, node.RemoveCmd.Flags().Set(commonflags.LocalDumpFlag, dumpPath))
|
||||
require.NoError(t, node.RemoveNodesCmd(node.RemoveCmd, []string{pub}))
|
||||
})
|
||||
}
|
||||
|
||||
func generateTestData(t *testing.T, dir string, size int) error {
|
||||
func generateTestData(dir string, size int) error {
|
||||
v := viper.GetViper()
|
||||
v.Set(alphabetWalletsFlag, dir)
|
||||
v.Set(commonflags.AlphabetWalletsFlag, dir)
|
||||
|
||||
sizeStr := strconv.FormatUint(uint64(size), 10)
|
||||
if err := generateAlphabetCmd.Flags().Set(alphabetSizeFlag, sizeStr); err != nil {
|
||||
if err := generate.GenerateAlphabetCmd.Flags().Set(commonflags.AlphabetSizeFlag, sizeStr); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
setTestCredentials(v, size)
|
||||
if err := generateAlphabetCreds(generateAlphabetCmd, nil); err != nil {
|
||||
if err := generate.AlphabetCreds(generate.GenerateAlphabetCmd, nil); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var pubs []string
|
||||
for i := 0; i < size; i++ {
|
||||
for i := range size {
|
||||
p := filepath.Join(dir, innerring.GlagoliticLetter(i).String()+".json")
|
||||
w, err := wallet.NewWalletFromFile(p)
|
||||
if err != nil {
|
||||
return fmt.Errorf("wallet doesn't exist: %w", err)
|
||||
}
|
||||
for _, acc := range w.Accounts {
|
||||
if acc.Label == singleAccountName {
|
||||
if acc.Label == constants.SingleAccountName {
|
||||
pub, ok := vm.ParseSignatureContract(acc.Contract.Script)
|
||||
if !ok {
|
||||
return fmt.Errorf("could not parse signature script for %s", acc.Address)
|
||||
|
@ -140,43 +148,8 @@ func generateTestData(t *testing.T, dir string, size int) error {
|
|||
}
|
||||
|
||||
func setTestCredentials(v *viper.Viper, size int) {
|
||||
for i := 0; i < size; i++ {
|
||||
for i := range size {
|
||||
v.Set("credentials."+innerring.GlagoliticLetter(i).String(), strconv.FormatUint(uint64(i), 10))
|
||||
}
|
||||
v.Set("credentials.contract", testContractPassword)
|
||||
}
|
||||
|
||||
func TestNextPollInterval(t *testing.T) {
|
||||
var pollInterval time.Duration
|
||||
var iteration int
|
||||
|
||||
pollInterval, hasChanged := nextPollInterval(iteration, pollInterval)
|
||||
require.True(t, hasChanged)
|
||||
require.Equal(t, time.Second, pollInterval)
|
||||
|
||||
iteration = 4
|
||||
pollInterval, hasChanged = nextPollInterval(iteration, pollInterval)
|
||||
require.False(t, hasChanged)
|
||||
require.Equal(t, time.Second, pollInterval)
|
||||
|
||||
iteration = 5
|
||||
pollInterval, hasChanged = nextPollInterval(iteration, pollInterval)
|
||||
require.True(t, hasChanged)
|
||||
require.Equal(t, 2*time.Second, pollInterval)
|
||||
|
||||
iteration = 10
|
||||
pollInterval, hasChanged = nextPollInterval(iteration, pollInterval)
|
||||
require.True(t, hasChanged)
|
||||
require.Equal(t, 4*time.Second, pollInterval)
|
||||
|
||||
iteration = 20
|
||||
pollInterval = 32 * time.Second
|
||||
pollInterval, hasChanged = nextPollInterval(iteration, pollInterval)
|
||||
require.True(t, hasChanged) // from 32s to 16s
|
||||
require.Equal(t, 16*time.Second, pollInterval)
|
||||
|
||||
pollInterval = 16 * time.Second
|
||||
pollInterval, hasChanged = nextPollInterval(iteration, pollInterval)
|
||||
require.False(t, hasChanged)
|
||||
require.Equal(t, 16*time.Second, pollInterval)
|
||||
v.Set("credentials.contract", constants.TestContractPassword)
|
||||
}
|
|
@ -1,9 +1,12 @@
|
|||
package morph
|
||||
package initialize
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/big"
|
||||
"strings"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/constants"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/helper"
|
||||
"github.com/nspcc-dev/neo-go/pkg/core/native"
|
||||
"github.com/nspcc-dev/neo-go/pkg/core/transaction"
|
||||
"github.com/nspcc-dev/neo-go/pkg/io"
|
||||
|
@ -12,7 +15,6 @@ import (
|
|||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/neo"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/nep17"
|
||||
"github.com/nspcc-dev/neo-go/pkg/smartcontract/callflag"
|
||||
scContext "github.com/nspcc-dev/neo-go/pkg/smartcontract/context"
|
||||
"github.com/nspcc-dev/neo-go/pkg/util"
|
||||
"github.com/nspcc-dev/neo-go/pkg/vm/emit"
|
||||
"github.com/nspcc-dev/neo-go/pkg/vm/opcode"
|
||||
|
@ -27,8 +29,12 @@ const (
|
|||
initialProxyGASAmount = 50_000 * native.GASFactor
|
||||
)
|
||||
|
||||
func (c *initializeContext) transferFunds() error {
|
||||
ok, err := c.transferFundsFinished()
|
||||
func initialCommitteeGASAmount(c *helper.InitializeContext) int64 {
|
||||
return (gasInitialTotalSupply - initialAlphabetGASAmount*int64(len(c.Wallets))) / 2
|
||||
}
|
||||
|
||||
func transferFunds(c *helper.InitializeContext) error {
|
||||
ok, err := transferFundsFinished(c)
|
||||
if ok || err != nil {
|
||||
if err == nil {
|
||||
c.Command.Println("Stage 1: already performed.")
|
||||
|
@ -53,7 +59,7 @@ func (c *initializeContext) transferFunds() error {
|
|||
transferTarget{
|
||||
Token: gas.Hash,
|
||||
Address: c.CommitteeAcc.Contract.ScriptHash(),
|
||||
Amount: (gasInitialTotalSupply - initialAlphabetGASAmount*int64(len(c.Wallets))) / 2,
|
||||
Amount: initialCommitteeGASAmount(c),
|
||||
},
|
||||
transferTarget{
|
||||
Token: neo.Hash,
|
||||
|
@ -67,83 +73,30 @@ func (c *initializeContext) transferFunds() error {
|
|||
return fmt.Errorf("can't create transfer transaction: %w", err)
|
||||
}
|
||||
|
||||
if err := c.multiSignAndSend(tx, consensusAccountName); err != nil {
|
||||
if err := c.MultiSignAndSend(tx, constants.ConsensusAccountName); err != nil {
|
||||
return fmt.Errorf("can't send transfer transaction: %w", err)
|
||||
}
|
||||
|
||||
return c.awaitTx()
|
||||
return c.AwaitTx()
|
||||
}
|
||||
|
||||
func (c *initializeContext) transferFundsFinished() (bool, error) {
|
||||
// transferFundsFinished checks balances of accounts we transfer GAS to.
|
||||
// The stage is considered finished if the balance is greater than the half of what we need to transfer.
|
||||
func transferFundsFinished(c *helper.InitializeContext) (bool, error) {
|
||||
acc := c.Accounts[0]
|
||||
|
||||
r := nep17.NewReader(c.ReadOnlyInvoker, gas.Hash)
|
||||
res, err := r.BalanceOf(acc.Contract.ScriptHash())
|
||||
return res.Cmp(big.NewInt(initialAlphabetGASAmount/2)) == 1, err
|
||||
if err != nil || res.Cmp(big.NewInt(initialAlphabetGASAmount/2)) != 1 {
|
||||
return false, err
|
||||
}
|
||||
|
||||
res, err = r.BalanceOf(c.CommitteeAcc.ScriptHash())
|
||||
return res != nil && res.Cmp(big.NewInt(initialCommitteeGASAmount(c)/2)) == 1, err
|
||||
}
|
||||
|
||||
func (c *initializeContext) multiSignAndSend(tx *transaction.Transaction, accType string) error {
|
||||
if err := c.multiSign(tx, accType); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.sendTx(tx, c.Command, false)
|
||||
}
|
||||
|
||||
func (c *initializeContext) multiSign(tx *transaction.Transaction, accType string) error {
|
||||
version, err := c.Client.GetVersion()
|
||||
if err != nil {
|
||||
// error appears only if client
|
||||
// has not been initialized
|
||||
panic(err)
|
||||
}
|
||||
network := version.Protocol.Network
|
||||
|
||||
// Use parameter context to avoid dealing with signature order.
|
||||
pc := scContext.NewParameterContext("", network, tx)
|
||||
h := c.CommitteeAcc.Contract.ScriptHash()
|
||||
if accType == consensusAccountName {
|
||||
h = c.ConsensusAcc.Contract.ScriptHash()
|
||||
}
|
||||
for _, w := range c.Wallets {
|
||||
acc, err := getWalletAccount(w, accType)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't find %s wallet account: %w", accType, err)
|
||||
}
|
||||
|
||||
priv := acc.PrivateKey()
|
||||
sign := priv.SignHashable(uint32(network), tx)
|
||||
if err := pc.AddSignature(h, acc.Contract, priv.PublicKey(), sign); err != nil {
|
||||
return fmt.Errorf("can't add signature: %w", err)
|
||||
}
|
||||
if len(pc.Items[h].Signatures) == len(acc.Contract.Parameters) {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
w, err := pc.GetWitness(h)
|
||||
if err != nil {
|
||||
return fmt.Errorf("incomplete signature: %w", err)
|
||||
}
|
||||
|
||||
for i := range tx.Signers {
|
||||
if tx.Signers[i].Account == h {
|
||||
if i < len(tx.Scripts) {
|
||||
tx.Scripts[i] = *w
|
||||
} else if i == len(tx.Scripts) {
|
||||
tx.Scripts = append(tx.Scripts, *w)
|
||||
} else {
|
||||
panic("BUG: invalid signing order")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("%s account was not found among transaction signers", accType)
|
||||
}
|
||||
|
||||
func (c *initializeContext) transferGASToProxy() error {
|
||||
proxyCs := c.getContract(proxyContract)
|
||||
func transferGASToProxy(c *helper.InitializeContext) error {
|
||||
proxyCs := c.GetContract(constants.ProxyContract)
|
||||
|
||||
r := nep17.NewReader(c.ReadOnlyInvoker, gas.Hash)
|
||||
bal, err := r.BalanceOf(proxyCs.Hash)
|
||||
|
@ -160,11 +113,11 @@ func (c *initializeContext) transferGASToProxy() error {
|
|||
return err
|
||||
}
|
||||
|
||||
if err := c.multiSignAndSend(tx, committeeAccountName); err != nil {
|
||||
if err := c.MultiSignAndSend(tx, constants.CommitteeAccountName); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return c.awaitTx()
|
||||
return c.AwaitTx()
|
||||
}
|
||||
|
||||
type transferTarget struct {
|
||||
|
@ -174,7 +127,7 @@ type transferTarget struct {
|
|||
Data any
|
||||
}
|
||||
|
||||
func createNEP17MultiTransferTx(c Client, acc *wallet.Account, recipients []transferTarget) (*transaction.Transaction, error) {
|
||||
func createNEP17MultiTransferTx(c helper.Client, acc *wallet.Account, recipients []transferTarget) (*transaction.Transaction, error) {
|
||||
from := acc.Contract.ScriptHash()
|
||||
|
||||
w := io.NewBufBinWriter()
|
||||
|
@ -199,5 +152,17 @@ func createNEP17MultiTransferTx(c Client, acc *wallet.Account, recipients []tran
|
|||
if err != nil {
|
||||
return nil, fmt.Errorf("can't create actor: %w", err)
|
||||
}
|
||||
return act.MakeRun(w.Bytes())
|
||||
tx, err := act.MakeRun(w.Bytes())
|
||||
if err != nil {
|
||||
sum := make(map[util.Uint160]int64)
|
||||
for _, recipient := range recipients {
|
||||
sum[recipient.Token] += recipient.Amount
|
||||
}
|
||||
detail := make([]string, 0, len(sum))
|
||||
for _, value := range sum {
|
||||
detail = append(detail, fmt.Sprintf("amount=%v", value))
|
||||
}
|
||||
err = fmt.Errorf("transfer failed: from=%s(%s) %s: %w", acc.Label, acc.Address, strings.Join(detail, " "), err)
|
||||
}
|
||||
return tx, err
|
||||
}
|
57
cmd/frostfs-adm/internal/modules/morph/initialize/root.go
Normal file
57
cmd/frostfs-adm/internal/modules/morph/initialize/root.go
Normal file
|
@ -0,0 +1,57 @@
|
|||
package initialize
|
||||
|
||||
import (
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
const (
|
||||
maxObjectSizeCLIFlag = "max-object-size"
|
||||
epochDurationCLIFlag = "epoch-duration"
|
||||
containerFeeCLIFlag = "container-fee"
|
||||
containerAliasFeeCLIFlag = "container-alias-fee"
|
||||
candidateFeeCLIFlag = "candidate-fee"
|
||||
homomorphicHashDisabledCLIFlag = "homomorphic-disabled"
|
||||
withdrawFeeCLIFlag = "withdraw-fee"
|
||||
)
|
||||
|
||||
var Cmd = &cobra.Command{
|
||||
Use: "init",
|
||||
Short: "Initialize side chain network with smart-contracts and network settings",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.AlphabetWalletsFlag, cmd.Flags().Lookup(commonflags.AlphabetWalletsFlag))
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
_ = viper.BindPFlag(commonflags.EpochDurationInitFlag, cmd.Flags().Lookup(epochDurationCLIFlag))
|
||||
_ = viper.BindPFlag(commonflags.MaxObjectSizeInitFlag, cmd.Flags().Lookup(maxObjectSizeCLIFlag))
|
||||
_ = viper.BindPFlag(commonflags.MaxECDataCountFlag, cmd.Flags().Lookup(commonflags.MaxECDataCountFlag))
|
||||
_ = viper.BindPFlag(commonflags.MaxECParityCounFlag, cmd.Flags().Lookup(commonflags.MaxECParityCounFlag))
|
||||
_ = viper.BindPFlag(commonflags.HomomorphicHashDisabledInitFlag, cmd.Flags().Lookup(homomorphicHashDisabledCLIFlag))
|
||||
_ = viper.BindPFlag(commonflags.CandidateFeeInitFlag, cmd.Flags().Lookup(candidateFeeCLIFlag))
|
||||
_ = viper.BindPFlag(commonflags.ContainerFeeInitFlag, cmd.Flags().Lookup(containerFeeCLIFlag))
|
||||
_ = viper.BindPFlag(commonflags.ContainerAliasFeeInitFlag, cmd.Flags().Lookup(containerAliasFeeCLIFlag))
|
||||
_ = viper.BindPFlag(commonflags.WithdrawFeeInitFlag, cmd.Flags().Lookup(withdrawFeeCLIFlag))
|
||||
_ = viper.BindPFlag(commonflags.ProtoConfigPath, cmd.Flags().Lookup(commonflags.ProtoConfigPath))
|
||||
},
|
||||
RunE: initializeSideChainCmd,
|
||||
}
|
||||
|
||||
func initInitCmd() {
|
||||
Cmd.Flags().String(commonflags.AlphabetWalletsFlag, "", commonflags.AlphabetWalletsFlagDesc)
|
||||
Cmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
Cmd.Flags().String(commonflags.ContractsInitFlag, "", commonflags.ContractsInitFlagDesc)
|
||||
Cmd.Flags().String(commonflags.ContractsURLFlag, "", commonflags.ContractsURLFlagDesc)
|
||||
Cmd.Flags().Uint(epochDurationCLIFlag, 240, "Amount of side chain blocks in one FrostFS epoch")
|
||||
Cmd.Flags().Uint(maxObjectSizeCLIFlag, 67108864, "Max single object size in bytes")
|
||||
Cmd.Flags().Bool(homomorphicHashDisabledCLIFlag, false, "Disable object homomorphic hashing")
|
||||
// Defaults are taken from neo-preodolenie.
|
||||
Cmd.Flags().Uint64(containerFeeCLIFlag, 1000, "Container registration fee")
|
||||
Cmd.Flags().Uint64(containerAliasFeeCLIFlag, 500, "Container alias fee")
|
||||
Cmd.Flags().String(commonflags.ProtoConfigPath, "", "Path to the consensus node configuration")
|
||||
Cmd.Flags().String(commonflags.LocalDumpFlag, "", "Path to the blocks dump file")
|
||||
Cmd.MarkFlagsMutuallyExclusive(commonflags.ContractsInitFlag, commonflags.ContractsURLFlag)
|
||||
}
|
||||
|
||||
func init() {
|
||||
initInitCmd()
|
||||
}
|
|
@ -1,675 +0,0 @@
|
|||
package morph
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"compress/gzip"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-contract/common"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-contract/nns"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/innerring"
|
||||
morphClient "git.frostfs.info/TrueCloudLab/frostfs-node/pkg/morph/client"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/morph/client/netmap"
|
||||
"github.com/nspcc-dev/neo-go/pkg/core/state"
|
||||
"github.com/nspcc-dev/neo-go/pkg/encoding/address"
|
||||
io2 "github.com/nspcc-dev/neo-go/pkg/io"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/actor"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/management"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/unwrap"
|
||||
"github.com/nspcc-dev/neo-go/pkg/smartcontract"
|
||||
"github.com/nspcc-dev/neo-go/pkg/smartcontract/callflag"
|
||||
"github.com/nspcc-dev/neo-go/pkg/smartcontract/manifest"
|
||||
"github.com/nspcc-dev/neo-go/pkg/smartcontract/nef"
|
||||
"github.com/nspcc-dev/neo-go/pkg/util"
|
||||
"github.com/nspcc-dev/neo-go/pkg/vm/emit"
|
||||
"github.com/nspcc-dev/neo-go/pkg/vm/opcode"
|
||||
"github.com/nspcc-dev/neo-go/pkg/vm/stackitem"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
const (
|
||||
nnsContract = "nns"
|
||||
frostfsContract = "frostfs" // not deployed in side-chain.
|
||||
processingContract = "processing" // not deployed in side-chain.
|
||||
alphabetContract = "alphabet"
|
||||
balanceContract = "balance"
|
||||
containerContract = "container"
|
||||
frostfsIDContract = "frostfsid"
|
||||
netmapContract = "netmap"
|
||||
policyContract = "policy"
|
||||
proxyContract = "proxy"
|
||||
)
|
||||
|
||||
const frostfsIDAdminConfigKey = "frostfsid.admin"
|
||||
|
||||
var (
|
||||
contractList = []string{
|
||||
balanceContract,
|
||||
containerContract,
|
||||
frostfsIDContract,
|
||||
netmapContract,
|
||||
policyContract,
|
||||
proxyContract,
|
||||
}
|
||||
|
||||
fullContractList = append([]string{
|
||||
frostfsContract,
|
||||
processingContract,
|
||||
nnsContract,
|
||||
alphabetContract,
|
||||
}, contractList...)
|
||||
|
||||
netmapConfigKeys = []string{
|
||||
netmap.EpochDurationConfig,
|
||||
netmap.MaxObjectSizeConfig,
|
||||
netmap.ContainerFeeConfig,
|
||||
netmap.ContainerAliasFeeConfig,
|
||||
netmap.IrCandidateFeeConfig,
|
||||
netmap.WithdrawFeeConfig,
|
||||
netmap.HomomorphicHashingDisabledKey,
|
||||
netmap.MaintenanceModeAllowedConfig,
|
||||
}
|
||||
)
|
||||
|
||||
type contractState struct {
|
||||
NEF *nef.File
|
||||
RawNEF []byte
|
||||
Manifest *manifest.Manifest
|
||||
RawManifest []byte
|
||||
Hash util.Uint160
|
||||
}
|
||||
|
||||
const (
|
||||
updateMethodName = "update"
|
||||
deployMethodName = "deploy"
|
||||
)
|
||||
|
||||
func domainOf(contract string) string {
|
||||
return contract + ".frostfs"
|
||||
}
|
||||
|
||||
func (c *initializeContext) deployNNS(method string) error {
|
||||
cs := c.getContract(nnsContract)
|
||||
h := cs.Hash
|
||||
|
||||
nnsCs, err := c.nnsContractState()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if nnsCs != nil {
|
||||
if nnsCs.NEF.Checksum == cs.NEF.Checksum {
|
||||
if method == deployMethodName {
|
||||
c.Command.Println("NNS contract is already deployed.")
|
||||
} else {
|
||||
c.Command.Println("NNS contract is already updated.")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
h = nnsCs.Hash
|
||||
}
|
||||
|
||||
err = c.addManifestGroup(h, cs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't sign manifest group: %v", err)
|
||||
}
|
||||
|
||||
params := getContractDeployParameters(cs, nil)
|
||||
|
||||
invokeHash := management.Hash
|
||||
if method == updateMethodName {
|
||||
invokeHash = nnsCs.Hash
|
||||
}
|
||||
|
||||
tx, err := c.CommitteeAct.MakeCall(invokeHash, method, params...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create deploy tx for %s: %w", nnsContract, err)
|
||||
}
|
||||
|
||||
if err := c.multiSignAndSend(tx, committeeAccountName); err != nil {
|
||||
return fmt.Errorf("can't send deploy transaction: %w", err)
|
||||
}
|
||||
|
||||
return c.awaitTx()
|
||||
}
|
||||
|
||||
func (c *initializeContext) updateContracts() error {
|
||||
alphaCs := c.getContract(alphabetContract)
|
||||
|
||||
nnsCs, err := c.nnsContractState()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
nnsHash := nnsCs.Hash
|
||||
|
||||
w := io2.NewBufBinWriter()
|
||||
|
||||
// Update script size for a single-node committee is close to the maximum allowed size of 65535.
|
||||
// Because of this we want to reuse alphabet contract NEF and manifest for different updates.
|
||||
// The generated script is as following.
|
||||
// 1. Initialize static slot for alphabet NEF.
|
||||
// 2. Store NEF into the static slot.
|
||||
// 3. Push parameters for each alphabet contract on stack.
|
||||
// 4. Add contract group to the manifest.
|
||||
// 5. For each alphabet contract, invoke `update` using parameters on stack and
|
||||
// NEF from step 2 and manifest from step 4.
|
||||
emit.Instruction(w.BinWriter, opcode.INITSSLOT, []byte{1})
|
||||
emit.Bytes(w.BinWriter, alphaCs.RawNEF)
|
||||
emit.Opcodes(w.BinWriter, opcode.STSFLD0)
|
||||
|
||||
keysParam, err := c.deployAlphabetAccounts(nnsHash, w, alphaCs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
w.Reset()
|
||||
|
||||
if err = c.deployOrUpdateContracts(w, nnsHash, keysParam); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
groupKey := c.ContractWallet.Accounts[0].PrivateKey().PublicKey()
|
||||
_, _, err = c.emitUpdateNNSGroupScript(w, nnsHash, groupKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.Command.Printf("NNS: Set %s -> %s\n", morphClient.NNSGroupKeyName, hex.EncodeToString(groupKey.Bytes()))
|
||||
|
||||
emit.Opcodes(w.BinWriter, opcode.LDSFLD0)
|
||||
emit.Int(w.BinWriter, 1)
|
||||
emit.Opcodes(w.BinWriter, opcode.PACK)
|
||||
emit.AppCallNoArgs(w.BinWriter, nnsHash, "setPrice", callflag.All)
|
||||
|
||||
if err := c.sendCommitteeTx(w.Bytes(), false); err != nil {
|
||||
return err
|
||||
}
|
||||
return c.awaitTx()
|
||||
}
|
||||
|
||||
func (c *initializeContext) deployOrUpdateContracts(w *io2.BufBinWriter, nnsHash util.Uint160, keysParam []any) error {
|
||||
emit.Instruction(w.BinWriter, opcode.INITSSLOT, []byte{1})
|
||||
emit.AppCall(w.BinWriter, nnsHash, "getPrice", callflag.All)
|
||||
emit.Opcodes(w.BinWriter, opcode.STSFLD0)
|
||||
emit.AppCall(w.BinWriter, nnsHash, "setPrice", callflag.All, 1)
|
||||
|
||||
for _, ctrName := range contractList {
|
||||
cs := c.getContract(ctrName)
|
||||
|
||||
method := updateMethodName
|
||||
ctrHash, err := nnsResolveHash(c.ReadOnlyInvoker, nnsHash, domainOf(ctrName))
|
||||
if err != nil {
|
||||
if errors.Is(err, errMissingNNSRecord) {
|
||||
// if contract not found we deploy it instead of update
|
||||
method = deployMethodName
|
||||
} else {
|
||||
return fmt.Errorf("can't resolve hash for contract update: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
err = c.addManifestGroup(ctrHash, cs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't sign manifest group: %v", err)
|
||||
}
|
||||
|
||||
invokeHash := management.Hash
|
||||
if method == updateMethodName {
|
||||
invokeHash = ctrHash
|
||||
}
|
||||
|
||||
args, err := c.getContractDeployData(ctrName, keysParam, updateMethodName)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s: getting update params: %v", ctrName, err)
|
||||
}
|
||||
params := getContractDeployParameters(cs, args)
|
||||
res, err := c.CommitteeAct.MakeCall(invokeHash, method, params...)
|
||||
if err != nil {
|
||||
if method != updateMethodName || !strings.Contains(err.Error(), common.ErrAlreadyUpdated) {
|
||||
return fmt.Errorf("deploy contract: %w", err)
|
||||
}
|
||||
c.Command.Printf("%s contract is already updated.\n", ctrName)
|
||||
continue
|
||||
}
|
||||
|
||||
w.WriteBytes(res.Script)
|
||||
|
||||
if method == deployMethodName {
|
||||
// same actions are done in initializeContext.setNNS, can be unified
|
||||
domain := ctrName + ".frostfs"
|
||||
script, ok, err := c.nnsRegisterDomainScript(nnsHash, cs.Hash, domain)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
w.WriteBytes(script)
|
||||
emit.AppCall(w.BinWriter, nnsHash, "deleteRecords", callflag.All, domain, int64(nns.TXT))
|
||||
emit.AppCall(w.BinWriter, nnsHash, "addRecord", callflag.All,
|
||||
domain, int64(nns.TXT), cs.Hash.StringLE())
|
||||
emit.AppCall(w.BinWriter, nnsHash, "addRecord", callflag.All,
|
||||
domain, int64(nns.TXT), address.Uint160ToString(cs.Hash))
|
||||
}
|
||||
c.Command.Printf("NNS: Set %s -> %s\n", domain, cs.Hash.StringLE())
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *initializeContext) deployAlphabetAccounts(nnsHash util.Uint160, w *io2.BufBinWriter, alphaCs *contractState) ([]any, error) {
|
||||
var keysParam []any
|
||||
|
||||
baseGroups := alphaCs.Manifest.Groups
|
||||
|
||||
// alphabet contracts should be deployed by individual nodes to get different hashes.
|
||||
for i, acc := range c.Accounts {
|
||||
ctrHash, err := nnsResolveHash(c.ReadOnlyInvoker, nnsHash, getAlphabetNNSDomain(i))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't resolve hash for contract update: %w", err)
|
||||
}
|
||||
|
||||
keysParam = append(keysParam, acc.PrivateKey().PublicKey().Bytes())
|
||||
|
||||
params := c.getAlphabetDeployItems(i, len(c.Wallets))
|
||||
emit.Array(w.BinWriter, params...)
|
||||
|
||||
alphaCs.Manifest.Groups = baseGroups
|
||||
err = c.addManifestGroup(ctrHash, alphaCs)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't sign manifest group: %v", err)
|
||||
}
|
||||
|
||||
emit.Bytes(w.BinWriter, alphaCs.RawManifest)
|
||||
emit.Opcodes(w.BinWriter, opcode.LDSFLD0)
|
||||
emit.Int(w.BinWriter, 3)
|
||||
emit.Opcodes(w.BinWriter, opcode.PACK)
|
||||
emit.AppCallNoArgs(w.BinWriter, ctrHash, updateMethodName, callflag.All)
|
||||
}
|
||||
if err := c.sendCommitteeTx(w.Bytes(), false); err != nil {
|
||||
if !strings.Contains(err.Error(), common.ErrAlreadyUpdated) {
|
||||
return nil, err
|
||||
}
|
||||
c.Command.Println("Alphabet contracts are already updated.")
|
||||
}
|
||||
|
||||
return keysParam, nil
|
||||
}
|
||||
|
||||
func (c *initializeContext) deployContracts() error {
|
||||
alphaCs := c.getContract(alphabetContract)
|
||||
|
||||
var keysParam []any
|
||||
|
||||
baseGroups := alphaCs.Manifest.Groups
|
||||
|
||||
// alphabet contracts should be deployed by individual nodes to get different hashes.
|
||||
for i, acc := range c.Accounts {
|
||||
ctrHash := state.CreateContractHash(acc.Contract.ScriptHash(), alphaCs.NEF.Checksum, alphaCs.Manifest.Name)
|
||||
if c.isUpdated(ctrHash, alphaCs) {
|
||||
c.Command.Printf("Alphabet contract #%d is already deployed.\n", i)
|
||||
continue
|
||||
}
|
||||
|
||||
alphaCs.Manifest.Groups = baseGroups
|
||||
err := c.addManifestGroup(ctrHash, alphaCs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't sign manifest group: %v", err)
|
||||
}
|
||||
|
||||
keysParam = append(keysParam, acc.PrivateKey().PublicKey().Bytes())
|
||||
params := getContractDeployParameters(alphaCs, c.getAlphabetDeployItems(i, len(c.Wallets)))
|
||||
|
||||
act, err := actor.NewSimple(c.Client, acc)
|
||||
if err != nil {
|
||||
return fmt.Errorf("could not create actor: %w", err)
|
||||
}
|
||||
|
||||
txHash, vub, err := act.SendCall(management.Hash, deployMethodName, params...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't deploy alphabet #%d contract: %w", i, err)
|
||||
}
|
||||
|
||||
c.SentTxs = append(c.SentTxs, hashVUBPair{hash: txHash, vub: vub})
|
||||
}
|
||||
|
||||
for _, ctrName := range contractList {
|
||||
cs := c.getContract(ctrName)
|
||||
|
||||
ctrHash := cs.Hash
|
||||
if c.isUpdated(ctrHash, cs) {
|
||||
c.Command.Printf("%s contract is already deployed.\n", ctrName)
|
||||
continue
|
||||
}
|
||||
|
||||
err := c.addManifestGroup(ctrHash, cs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't sign manifest group: %v", err)
|
||||
}
|
||||
|
||||
args, err := c.getContractDeployData(ctrName, keysParam, deployMethodName)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s: getting deploy params: %v", ctrName, err)
|
||||
}
|
||||
params := getContractDeployParameters(cs, args)
|
||||
res, err := c.CommitteeAct.MakeCall(management.Hash, deployMethodName, params...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't deploy %s contract: %w", ctrName, err)
|
||||
}
|
||||
|
||||
if err := c.sendCommitteeTx(res.Script, false); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return c.awaitTx()
|
||||
}
|
||||
|
||||
func (c *initializeContext) isUpdated(ctrHash util.Uint160, cs *contractState) bool {
|
||||
r := management.NewReader(c.ReadOnlyInvoker)
|
||||
realCs, err := r.GetContract(ctrHash)
|
||||
return err == nil && realCs != nil && realCs.NEF.Checksum == cs.NEF.Checksum
|
||||
}
|
||||
|
||||
func (c *initializeContext) getContract(ctrName string) *contractState {
|
||||
return c.Contracts[ctrName]
|
||||
}
|
||||
|
||||
func (c *initializeContext) readContracts(names []string) error {
|
||||
var (
|
||||
fi os.FileInfo
|
||||
err error
|
||||
)
|
||||
if c.ContractPath != "" {
|
||||
fi, err = os.Stat(c.ContractPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid contracts path: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if c.ContractPath != "" && fi.IsDir() {
|
||||
for _, ctrName := range names {
|
||||
cs, err := readContract(filepath.Join(c.ContractPath, ctrName), ctrName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.Contracts[ctrName] = cs
|
||||
}
|
||||
} else {
|
||||
var r io.ReadCloser
|
||||
if c.ContractPath == "" {
|
||||
return errors.New("contracts flag is missing")
|
||||
}
|
||||
r, err = os.Open(c.ContractPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't open contracts archive: %w", err)
|
||||
}
|
||||
defer r.Close()
|
||||
|
||||
m, err := readContractsFromArchive(r, names)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, name := range names {
|
||||
if err := m[name].parse(); err != nil {
|
||||
return err
|
||||
}
|
||||
c.Contracts[name] = m[name]
|
||||
}
|
||||
}
|
||||
|
||||
for _, ctrName := range names {
|
||||
if ctrName != alphabetContract {
|
||||
cs := c.Contracts[ctrName]
|
||||
cs.Hash = state.CreateContractHash(c.CommitteeAcc.Contract.ScriptHash(),
|
||||
cs.NEF.Checksum, cs.Manifest.Name)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func readContract(ctrPath, ctrName string) (*contractState, error) {
|
||||
rawNef, err := os.ReadFile(filepath.Join(ctrPath, ctrName+"_contract.nef"))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't read NEF file for %s contract: %w", ctrName, err)
|
||||
}
|
||||
rawManif, err := os.ReadFile(filepath.Join(ctrPath, "config.json"))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't read manifest file for %s contract: %w", ctrName, err)
|
||||
}
|
||||
|
||||
cs := &contractState{
|
||||
RawNEF: rawNef,
|
||||
RawManifest: rawManif,
|
||||
}
|
||||
|
||||
return cs, cs.parse()
|
||||
}
|
||||
|
||||
func (cs *contractState) parse() error {
|
||||
nf, err := nef.FileFromBytes(cs.RawNEF)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't parse NEF file: %w", err)
|
||||
}
|
||||
|
||||
m := new(manifest.Manifest)
|
||||
if err := json.Unmarshal(cs.RawManifest, m); err != nil {
|
||||
return fmt.Errorf("can't parse manifest file: %w", err)
|
||||
}
|
||||
|
||||
cs.NEF = &nf
|
||||
cs.Manifest = m
|
||||
return nil
|
||||
}
|
||||
|
||||
func readContractsFromArchive(file io.Reader, names []string) (map[string]*contractState, error) {
|
||||
m := make(map[string]*contractState, len(names))
|
||||
for i := range names {
|
||||
m[names[i]] = new(contractState)
|
||||
}
|
||||
|
||||
gr, err := gzip.NewReader(file)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("contracts file must be tar.gz archive: %w", err)
|
||||
}
|
||||
|
||||
r := tar.NewReader(gr)
|
||||
for h, err := r.Next(); ; h, err = r.Next() {
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
|
||||
dir, _ := filepath.Split(h.Name)
|
||||
ctrName := filepath.Base(dir)
|
||||
|
||||
cs, ok := m[ctrName]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
switch {
|
||||
case strings.HasSuffix(h.Name, filepath.Join(ctrName, ctrName+"_contract.nef")):
|
||||
cs.RawNEF, err = io.ReadAll(r)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't read NEF file for %s contract: %w", ctrName, err)
|
||||
}
|
||||
case strings.HasSuffix(h.Name, "config.json"):
|
||||
cs.RawManifest, err = io.ReadAll(r)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't read manifest file for %s contract: %w", ctrName, err)
|
||||
}
|
||||
}
|
||||
m[ctrName] = cs
|
||||
}
|
||||
|
||||
for ctrName, cs := range m {
|
||||
if cs.RawNEF == nil {
|
||||
return nil, fmt.Errorf("NEF for %s contract wasn't found", ctrName)
|
||||
}
|
||||
if cs.RawManifest == nil {
|
||||
return nil, fmt.Errorf("manifest for %s contract wasn't found", ctrName)
|
||||
}
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func getContractDeployParameters(cs *contractState, deployData []any) []any {
|
||||
return []any{cs.RawNEF, cs.RawManifest, deployData}
|
||||
}
|
||||
|
||||
func (c *initializeContext) getContractDeployData(ctrName string, keysParam []any, method string) ([]any, error) {
|
||||
items := make([]any, 0, 6)
|
||||
|
||||
switch ctrName {
|
||||
case frostfsContract:
|
||||
items = append(items,
|
||||
c.Contracts[processingContract].Hash,
|
||||
keysParam,
|
||||
smartcontract.Parameter{})
|
||||
case processingContract:
|
||||
items = append(items, c.Contracts[frostfsContract].Hash)
|
||||
return items[1:], nil // no notary info
|
||||
case balanceContract:
|
||||
items = append(items,
|
||||
c.Contracts[netmapContract].Hash,
|
||||
c.Contracts[containerContract].Hash)
|
||||
case containerContract:
|
||||
// In case if NNS is updated multiple times, we can't calculate
|
||||
// it's actual hash based on local data, thus query chain.
|
||||
r := management.NewReader(c.ReadOnlyInvoker)
|
||||
nnsCs, err := r.GetContractByID(1)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get nns contract: %w", err)
|
||||
}
|
||||
items = append(items,
|
||||
c.Contracts[netmapContract].Hash,
|
||||
c.Contracts[balanceContract].Hash,
|
||||
c.Contracts[frostfsIDContract].Hash,
|
||||
nnsCs.Hash,
|
||||
"container")
|
||||
case frostfsIDContract:
|
||||
var (
|
||||
h util.Uint160
|
||||
found bool
|
||||
err error
|
||||
)
|
||||
if method == updateMethodName {
|
||||
h, found, err = c.getFrostfsIDAdminFromContract()
|
||||
}
|
||||
if method != updateMethodName || err == nil && !found {
|
||||
h, found, err = getFrostfsIDAdmin(viper.GetViper())
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if found {
|
||||
items = append(items, h)
|
||||
} else {
|
||||
items = append(items, c.Contracts[proxyContract].Hash)
|
||||
}
|
||||
case netmapContract:
|
||||
md := getDefaultNetmapContractConfigMap()
|
||||
if method == updateMethodName {
|
||||
if err := c.mergeNetmapConfig(md); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
var configParam []any
|
||||
for k, v := range md {
|
||||
configParam = append(configParam, k, v)
|
||||
}
|
||||
|
||||
items = append(items,
|
||||
c.Contracts[balanceContract].Hash,
|
||||
c.Contracts[containerContract].Hash,
|
||||
keysParam,
|
||||
configParam)
|
||||
case proxyContract:
|
||||
items = nil
|
||||
case policyContract:
|
||||
items = append(items, c.Contracts[proxyContract].Hash)
|
||||
default:
|
||||
panic(fmt.Sprintf("invalid contract name: %s", ctrName))
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func (c *initializeContext) getFrostfsIDAdminFromContract() (util.Uint160, bool, error) {
|
||||
r := management.NewReader(c.ReadOnlyInvoker)
|
||||
cs, err := r.GetContractByID(1)
|
||||
if err != nil {
|
||||
return util.Uint160{}, false, fmt.Errorf("get nns contract: %w", err)
|
||||
}
|
||||
fidHash, err := nnsResolveHash(c.ReadOnlyInvoker, cs.Hash, domainOf(frostfsIDContract))
|
||||
if err != nil {
|
||||
return util.Uint160{}, false, fmt.Errorf("resolve frostfsid contract hash: %w", err)
|
||||
}
|
||||
item, err := unwrap.Item(c.ReadOnlyInvoker.Call(fidHash, "getAdmin"))
|
||||
if err != nil {
|
||||
return util.Uint160{}, false, fmt.Errorf("getAdmin: %w", err)
|
||||
}
|
||||
if _, ok := item.(stackitem.Null); ok {
|
||||
return util.Uint160{}, false, nil
|
||||
}
|
||||
|
||||
bs, err := item.TryBytes()
|
||||
if err != nil {
|
||||
return util.Uint160{}, true, fmt.Errorf("getAdmin: decode result: %w", err)
|
||||
}
|
||||
h, err := util.Uint160DecodeBytesBE(bs)
|
||||
if err != nil {
|
||||
return util.Uint160{}, true, fmt.Errorf("getAdmin: decode result: %w", err)
|
||||
}
|
||||
return h, true, nil
|
||||
}
|
||||
|
||||
func (c *initializeContext) getNetConfigFromNetmapContract() ([]stackitem.Item, error) {
|
||||
r := management.NewReader(c.ReadOnlyInvoker)
|
||||
cs, err := r.GetContractByID(1)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get nns contract: %w", err)
|
||||
}
|
||||
nmHash, err := nnsResolveHash(c.ReadOnlyInvoker, cs.Hash, domainOf(netmapContract))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't get netmap contract hash: %w", err)
|
||||
}
|
||||
arr, err := unwrap.Array(c.ReadOnlyInvoker.Call(nmHash, "listConfig"))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("can't fetch list of network config keys from the netmap contract")
|
||||
}
|
||||
return arr, err
|
||||
}
|
||||
|
||||
func (c *initializeContext) mergeNetmapConfig(md map[string]any) error {
|
||||
arr, err := c.getNetConfigFromNetmapContract()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
m, err := parseConfigFromNetmapContract(arr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for k, v := range m {
|
||||
for _, key := range netmapConfigKeys {
|
||||
if k == key {
|
||||
md[k] = v
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *initializeContext) getAlphabetDeployItems(i, n int) []any {
|
||||
items := make([]any, 5)
|
||||
items[0] = c.Contracts[netmapContract].Hash
|
||||
items[1] = c.Contracts[proxyContract].Hash
|
||||
items[2] = innerring.GlagoliticLetter(i).String()
|
||||
items[3] = int64(i)
|
||||
items[4] = int64(n)
|
||||
return items
|
||||
}
|
|
@ -1,305 +0,0 @@
|
|||
package morph
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-contract/nns"
|
||||
morphClient "git.frostfs.info/TrueCloudLab/frostfs-node/pkg/morph/client"
|
||||
"github.com/nspcc-dev/neo-go/pkg/core/state"
|
||||
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
|
||||
"github.com/nspcc-dev/neo-go/pkg/encoding/address"
|
||||
"github.com/nspcc-dev/neo-go/pkg/io"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/invoker"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/management"
|
||||
nnsClient "github.com/nspcc-dev/neo-go/pkg/rpcclient/nns"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/unwrap"
|
||||
"github.com/nspcc-dev/neo-go/pkg/smartcontract/callflag"
|
||||
"github.com/nspcc-dev/neo-go/pkg/util"
|
||||
"github.com/nspcc-dev/neo-go/pkg/vm/emit"
|
||||
"github.com/nspcc-dev/neo-go/pkg/vm/opcode"
|
||||
"github.com/nspcc-dev/neo-go/pkg/vm/stackitem"
|
||||
"github.com/nspcc-dev/neo-go/pkg/vm/vmstate"
|
||||
)
|
||||
|
||||
const defaultExpirationTime = 10 * 365 * 24 * time.Hour / time.Second
|
||||
|
||||
const frostfsOpsEmail = "ops@frostfs.info"
|
||||
|
||||
func (c *initializeContext) setNNS() error {
|
||||
r := management.NewReader(c.ReadOnlyInvoker)
|
||||
nnsCs, err := r.GetContractByID(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ok, err := c.nnsRootRegistered(nnsCs.Hash, "frostfs")
|
||||
if err != nil {
|
||||
return err
|
||||
} else if !ok {
|
||||
bw := io.NewBufBinWriter()
|
||||
emit.AppCall(bw.BinWriter, nnsCs.Hash, "register", callflag.All,
|
||||
"frostfs", c.CommitteeAcc.Contract.ScriptHash(),
|
||||
frostfsOpsEmail, int64(3600), int64(600), int64(defaultExpirationTime), int64(3600))
|
||||
emit.Opcodes(bw.BinWriter, opcode.ASSERT)
|
||||
if err := c.sendCommitteeTx(bw.Bytes(), true); err != nil {
|
||||
return fmt.Errorf("can't add domain root to NNS: %w", err)
|
||||
}
|
||||
if err := c.awaitTx(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
alphaCs := c.getContract(alphabetContract)
|
||||
for i, acc := range c.Accounts {
|
||||
alphaCs.Hash = state.CreateContractHash(acc.Contract.ScriptHash(), alphaCs.NEF.Checksum, alphaCs.Manifest.Name)
|
||||
|
||||
domain := getAlphabetNNSDomain(i)
|
||||
if err := c.nnsRegisterDomain(nnsCs.Hash, alphaCs.Hash, domain); err != nil {
|
||||
return err
|
||||
}
|
||||
c.Command.Printf("NNS: Set %s -> %s\n", domain, alphaCs.Hash.StringLE())
|
||||
}
|
||||
|
||||
for _, ctrName := range contractList {
|
||||
cs := c.getContract(ctrName)
|
||||
|
||||
domain := ctrName + ".frostfs"
|
||||
if err := c.nnsRegisterDomain(nnsCs.Hash, cs.Hash, domain); err != nil {
|
||||
return err
|
||||
}
|
||||
c.Command.Printf("NNS: Set %s -> %s\n", domain, cs.Hash.StringLE())
|
||||
}
|
||||
|
||||
groupKey := c.ContractWallet.Accounts[0].PrivateKey().PublicKey()
|
||||
err = c.updateNNSGroup(nnsCs.Hash, groupKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.Command.Printf("NNS: Set %s -> %s\n", morphClient.NNSGroupKeyName, hex.EncodeToString(groupKey.Bytes()))
|
||||
|
||||
return c.awaitTx()
|
||||
}
|
||||
|
||||
func (c *initializeContext) updateNNSGroup(nnsHash util.Uint160, pub *keys.PublicKey) error {
|
||||
bw := io.NewBufBinWriter()
|
||||
keyAlreadyAdded, domainRegCodeEmitted, err := c.emitUpdateNNSGroupScript(bw, nnsHash, pub)
|
||||
if keyAlreadyAdded || err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
script := bw.Bytes()
|
||||
if domainRegCodeEmitted {
|
||||
w := io.NewBufBinWriter()
|
||||
emit.Instruction(w.BinWriter, opcode.INITSSLOT, []byte{1})
|
||||
wrapRegisterScriptWithPrice(w, nnsHash, script)
|
||||
script = w.Bytes()
|
||||
}
|
||||
|
||||
return c.sendCommitteeTx(script, true)
|
||||
}
|
||||
|
||||
// emitUpdateNNSGroupScript emits script for updating group key stored in NNS.
|
||||
// First return value is true iff the key is already there and nothing should be done.
|
||||
// Second return value is true iff a domain registration code was emitted.
|
||||
func (c *initializeContext) emitUpdateNNSGroupScript(bw *io.BufBinWriter, nnsHash util.Uint160, pub *keys.PublicKey) (bool, bool, error) {
|
||||
isAvail, err := nnsIsAvailable(c.Client, nnsHash, morphClient.NNSGroupKeyName)
|
||||
if err != nil {
|
||||
return false, false, err
|
||||
}
|
||||
|
||||
if !isAvail {
|
||||
currentPub, err := nnsResolveKey(c.ReadOnlyInvoker, nnsHash, morphClient.NNSGroupKeyName)
|
||||
if err != nil {
|
||||
return false, false, err
|
||||
}
|
||||
|
||||
if pub.Equal(currentPub) {
|
||||
return true, false, nil
|
||||
}
|
||||
}
|
||||
|
||||
if isAvail {
|
||||
emit.AppCall(bw.BinWriter, nnsHash, "register", callflag.All,
|
||||
morphClient.NNSGroupKeyName, c.CommitteeAcc.Contract.ScriptHash(),
|
||||
frostfsOpsEmail, int64(3600), int64(600), int64(defaultExpirationTime), int64(3600))
|
||||
emit.Opcodes(bw.BinWriter, opcode.ASSERT)
|
||||
}
|
||||
|
||||
emit.AppCall(bw.BinWriter, nnsHash, "deleteRecords", callflag.All, "group.frostfs", int64(nns.TXT))
|
||||
emit.AppCall(bw.BinWriter, nnsHash, "addRecord", callflag.All,
|
||||
"group.frostfs", int64(nns.TXT), hex.EncodeToString(pub.Bytes()))
|
||||
|
||||
return false, isAvail, nil
|
||||
}
|
||||
|
||||
func getAlphabetNNSDomain(i int) string {
|
||||
return alphabetContract + strconv.FormatUint(uint64(i), 10) + ".frostfs"
|
||||
}
|
||||
|
||||
// wrapRegisterScriptWithPrice wraps a given script with `getPrice`/`setPrice` calls for NNS.
|
||||
// It is intended to be used for a single transaction, and not as a part of other scripts.
|
||||
// It is assumed that script already contains static slot initialization code, the first one
|
||||
// (with index 0) is used to store the price.
|
||||
func wrapRegisterScriptWithPrice(w *io.BufBinWriter, nnsHash util.Uint160, s []byte) {
|
||||
if len(s) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
emit.AppCall(w.BinWriter, nnsHash, "getPrice", callflag.All)
|
||||
emit.Opcodes(w.BinWriter, opcode.STSFLD0)
|
||||
emit.AppCall(w.BinWriter, nnsHash, "setPrice", callflag.All, 1)
|
||||
|
||||
w.WriteBytes(s)
|
||||
|
||||
emit.Opcodes(w.BinWriter, opcode.LDSFLD0, opcode.PUSH1, opcode.PACK)
|
||||
emit.AppCallNoArgs(w.BinWriter, nnsHash, "setPrice", callflag.All)
|
||||
|
||||
if w.Err != nil {
|
||||
panic(fmt.Errorf("BUG: can't wrap register script: %w", w.Err))
|
||||
}
|
||||
}
|
||||
|
||||
func (c *initializeContext) nnsRegisterDomainScript(nnsHash, expectedHash util.Uint160, domain string) ([]byte, bool, error) {
|
||||
ok, err := nnsIsAvailable(c.Client, nnsHash, domain)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
|
||||
if ok {
|
||||
bw := io.NewBufBinWriter()
|
||||
emit.AppCall(bw.BinWriter, nnsHash, "register", callflag.All,
|
||||
domain, c.CommitteeAcc.Contract.ScriptHash(),
|
||||
frostfsOpsEmail, int64(3600), int64(600), int64(defaultExpirationTime), int64(3600))
|
||||
emit.Opcodes(bw.BinWriter, opcode.ASSERT)
|
||||
|
||||
if bw.Err != nil {
|
||||
panic(bw.Err)
|
||||
}
|
||||
return bw.Bytes(), false, nil
|
||||
}
|
||||
|
||||
s, err := nnsResolveHash(c.ReadOnlyInvoker, nnsHash, domain)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
return nil, s == expectedHash, nil
|
||||
}
|
||||
|
||||
func (c *initializeContext) nnsRegisterDomain(nnsHash, expectedHash util.Uint160, domain string) error {
|
||||
script, ok, err := c.nnsRegisterDomainScript(nnsHash, expectedHash, domain)
|
||||
if ok || err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
w := io.NewBufBinWriter()
|
||||
emit.Instruction(w.BinWriter, opcode.INITSSLOT, []byte{1})
|
||||
wrapRegisterScriptWithPrice(w, nnsHash, script)
|
||||
|
||||
emit.AppCall(w.BinWriter, nnsHash, "deleteRecords", callflag.All, domain, int64(nns.TXT))
|
||||
emit.AppCall(w.BinWriter, nnsHash, "addRecord", callflag.All,
|
||||
domain, int64(nns.TXT), expectedHash.StringLE())
|
||||
emit.AppCall(w.BinWriter, nnsHash, "addRecord", callflag.All,
|
||||
domain, int64(nns.TXT), address.Uint160ToString(expectedHash))
|
||||
return c.sendCommitteeTx(w.Bytes(), true)
|
||||
}
|
||||
|
||||
func (c *initializeContext) nnsRootRegistered(nnsHash util.Uint160, zone string) (bool, error) {
|
||||
res, err := c.CommitteeAct.Call(nnsHash, "isAvailable", "name."+zone)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
return res.State == vmstate.Halt.String(), nil
|
||||
}
|
||||
|
||||
var errMissingNNSRecord = errors.New("missing NNS record")
|
||||
|
||||
// Returns errMissingNNSRecord if invocation fault exception contains "token not found".
|
||||
func nnsResolveHash(inv *invoker.Invoker, nnsHash util.Uint160, domain string) (util.Uint160, error) {
|
||||
item, err := nnsResolve(inv, nnsHash, domain)
|
||||
if err != nil {
|
||||
return util.Uint160{}, err
|
||||
}
|
||||
return parseNNSResolveResult(item)
|
||||
}
|
||||
|
||||
func nnsResolve(inv *invoker.Invoker, nnsHash util.Uint160, domain string) (stackitem.Item, error) {
|
||||
return unwrap.Item(inv.Call(nnsHash, "resolve", domain, int64(nns.TXT)))
|
||||
}
|
||||
|
||||
func nnsResolveKey(inv *invoker.Invoker, nnsHash util.Uint160, domain string) (*keys.PublicKey, error) {
|
||||
res, err := nnsResolve(inv, nnsHash, domain)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, ok := res.Value().(stackitem.Null); ok {
|
||||
return nil, errors.New("NNS record is missing")
|
||||
}
|
||||
arr, ok := res.Value().([]stackitem.Item)
|
||||
if !ok {
|
||||
return nil, errors.New("API of the NNS contract method `resolve` has changed")
|
||||
}
|
||||
for i := range arr {
|
||||
var bs []byte
|
||||
bs, err = arr[i].TryBytes()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
return keys.NewPublicKeyFromString(string(bs))
|
||||
}
|
||||
return nil, errors.New("no valid keys are found")
|
||||
}
|
||||
|
||||
// parseNNSResolveResult parses the result of resolving NNS record.
|
||||
// It works with multiple formats (corresponding to multiple NNS versions).
|
||||
// If array of hashes is provided, it returns only the first one.
|
||||
func parseNNSResolveResult(res stackitem.Item) (util.Uint160, error) {
|
||||
arr, ok := res.Value().([]stackitem.Item)
|
||||
if !ok {
|
||||
arr = []stackitem.Item{res}
|
||||
}
|
||||
if _, ok := res.Value().(stackitem.Null); ok || len(arr) == 0 {
|
||||
return util.Uint160{}, errors.New("NNS record is missing")
|
||||
}
|
||||
for i := range arr {
|
||||
bs, err := arr[i].TryBytes()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// We support several formats for hash encoding, this logic should be maintained in sync
|
||||
// with nnsResolve from pkg/morph/client/nns.go
|
||||
h, err := util.Uint160DecodeStringLE(string(bs))
|
||||
if err == nil {
|
||||
return h, nil
|
||||
}
|
||||
|
||||
h, err = address.StringToUint160(string(bs))
|
||||
if err == nil {
|
||||
return h, nil
|
||||
}
|
||||
}
|
||||
return util.Uint160{}, errors.New("no valid hashes are found")
|
||||
}
|
||||
|
||||
func nnsIsAvailable(c Client, nnsHash util.Uint160, name string) (bool, error) {
|
||||
switch c.(type) {
|
||||
case *rpcclient.Client:
|
||||
inv := invoker.New(c, nil)
|
||||
reader := nnsClient.NewReader(inv, nnsHash)
|
||||
return reader.IsAvailable(name)
|
||||
default:
|
||||
b, err := unwrap.Bool(invokeFunction(c, nnsHash, "isAvailable", []any{name}, nil))
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("`isAvailable`: invalid response: %w", err)
|
||||
}
|
||||
|
||||
return b, nil
|
||||
}
|
||||
}
|
48
cmd/frostfs-adm/internal/modules/morph/netmap/epoch.go
Normal file
48
cmd/frostfs-adm/internal/modules/morph/netmap/epoch.go
Normal file
|
@ -0,0 +1,48 @@
|
|||
package netmap
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/constants"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/helper"
|
||||
"github.com/nspcc-dev/neo-go/pkg/io"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/management"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
const deltaFlag = "delta"
|
||||
|
||||
func ForceNewEpochCmd(cmd *cobra.Command, _ []string) error {
|
||||
wCtx, err := helper.NewInitializeContext(cmd, viper.GetViper())
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't initialize context: %w", err)
|
||||
}
|
||||
|
||||
r := management.NewReader(wCtx.ReadOnlyInvoker)
|
||||
cs, err := helper.GetContractByID(r, 1)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't get NNS contract info: %w", err)
|
||||
}
|
||||
|
||||
nmHash, err := helper.NNSResolveHash(wCtx.ReadOnlyInvoker, cs.Hash, helper.DomainOf(constants.NetmapContract))
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't get netmap contract hash: %w", err)
|
||||
}
|
||||
|
||||
bw := io.NewBufBinWriter()
|
||||
delta, _ := cmd.Flags().GetInt64(deltaFlag)
|
||||
if err := helper.EmitNewEpochCall(bw, wCtx, nmHash, delta); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err = wCtx.SendConsensusTx(bw.Bytes()); err == nil {
|
||||
err = wCtx.AwaitTx()
|
||||
}
|
||||
if err != nil && strings.Contains(err.Error(), "invalid epoch") {
|
||||
cmd.Println("Epoch has already ticked.")
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
|
@ -1,7 +1,9 @@
|
|||
package morph
|
||||
package netmap
|
||||
|
||||
import (
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/constants"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/helper"
|
||||
commonCmd "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/internal/common"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/morph/client/netmap"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/invoker"
|
||||
|
@ -11,16 +13,16 @@ import (
|
|||
)
|
||||
|
||||
func listNetmapCandidatesNodes(cmd *cobra.Command, _ []string) {
|
||||
c, err := getN3Client(viper.GetViper())
|
||||
c, err := helper.NewRemoteClient(viper.GetViper())
|
||||
commonCmd.ExitOnErr(cmd, "can't create N3 client: %w", err)
|
||||
|
||||
inv := invoker.New(c, nil)
|
||||
r := management.NewReader(inv)
|
||||
|
||||
cs, err := r.GetContractByID(1)
|
||||
cs, err := helper.GetContractByID(r, 1)
|
||||
commonCmd.ExitOnErr(cmd, "can't get NNS contract info: %w", err)
|
||||
|
||||
nmHash, err := nnsResolveHash(inv, cs.Hash, domainOf(netmapContract))
|
||||
nmHash, err := helper.NNSResolveHash(inv, cs.Hash, helper.DomainOf(constants.NetmapContract))
|
||||
commonCmd.ExitOnErr(cmd, "can't get netmap contract hash: %w", err)
|
||||
|
||||
res, err := inv.Call(nmHash, "netmapCandidates")
|
43
cmd/frostfs-adm/internal/modules/morph/netmap/root.go
Normal file
43
cmd/frostfs-adm/internal/modules/morph/netmap/root.go
Normal file
|
@ -0,0 +1,43 @@
|
|||
package netmap
|
||||
|
||||
import (
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var (
|
||||
CandidatesCmd = &cobra.Command{
|
||||
Use: "netmap-candidates",
|
||||
Short: "List netmap candidates nodes",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
Run: listNetmapCandidatesNodes,
|
||||
}
|
||||
ForceNewEpoch = &cobra.Command{
|
||||
Use: "force-new-epoch",
|
||||
Short: "Create new FrostFS epoch event in the side chain",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.AlphabetWalletsFlag, cmd.Flags().Lookup(commonflags.AlphabetWalletsFlag))
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
RunE: ForceNewEpochCmd,
|
||||
}
|
||||
)
|
||||
|
||||
func initNetmapCandidatesCmd() {
|
||||
CandidatesCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
}
|
||||
|
||||
func initForceNewEpochCmd() {
|
||||
ForceNewEpoch.Flags().String(commonflags.AlphabetWalletsFlag, "", commonflags.AlphabetWalletsFlagDesc)
|
||||
ForceNewEpoch.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
ForceNewEpoch.Flags().String(commonflags.LocalDumpFlag, "", "Path to the blocks dump file")
|
||||
ForceNewEpoch.Flags().Int64(deltaFlag, 1, "Number of epochs to increase the current epoch")
|
||||
}
|
||||
|
||||
func init() {
|
||||
initNetmapCandidatesCmd()
|
||||
initForceNewEpochCmd()
|
||||
}
|
|
@ -1,44 +0,0 @@
|
|||
package morph
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/pkg/morph/client/netmap"
|
||||
"github.com/nspcc-dev/neo-go/pkg/vm/stackitem"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
func getDefaultNetmapContractConfigMap() map[string]any {
|
||||
m := make(map[string]any)
|
||||
m[netmap.EpochDurationConfig] = viper.GetInt64(epochDurationInitFlag)
|
||||
m[netmap.MaxObjectSizeConfig] = viper.GetInt64(maxObjectSizeInitFlag)
|
||||
m[netmap.ContainerFeeConfig] = viper.GetInt64(containerFeeInitFlag)
|
||||
m[netmap.ContainerAliasFeeConfig] = viper.GetInt64(containerAliasFeeInitFlag)
|
||||
m[netmap.IrCandidateFeeConfig] = viper.GetInt64(candidateFeeInitFlag)
|
||||
m[netmap.WithdrawFeeConfig] = viper.GetInt64(withdrawFeeInitFlag)
|
||||
m[netmap.HomomorphicHashingDisabledKey] = viper.GetBool(homomorphicHashDisabledInitFlag)
|
||||
m[netmap.MaintenanceModeAllowedConfig] = viper.GetBool(maintenanceModeAllowedInitFlag)
|
||||
return m
|
||||
}
|
||||
|
||||
func parseConfigFromNetmapContract(arr []stackitem.Item) (map[string][]byte, error) {
|
||||
m := make(map[string][]byte, len(arr))
|
||||
for _, param := range arr {
|
||||
tuple, ok := param.Value().([]stackitem.Item)
|
||||
if !ok || len(tuple) != 2 {
|
||||
return nil, errors.New("invalid ListConfig response from netmap contract")
|
||||
}
|
||||
|
||||
k, err := tuple[0].TryBytes()
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid config key from netmap contract")
|
||||
}
|
||||
|
||||
v, err := tuple[1].TryBytes()
|
||||
if err != nil {
|
||||
return nil, invalidConfigValueErr(string(k))
|
||||
}
|
||||
m[string(k)] = v
|
||||
}
|
||||
return m, nil
|
||||
}
|
64
cmd/frostfs-adm/internal/modules/morph/nns/domains.go
Normal file
64
cmd/frostfs-adm/internal/modules/morph/nns/domains.go
Normal file
|
@ -0,0 +1,64 @@
|
|||
package nns
|
||||
|
||||
import (
|
||||
"math/big"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/constants"
|
||||
commonCmd "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/internal/common"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func initRegisterCmd() {
|
||||
Cmd.AddCommand(registerCmd)
|
||||
registerCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
registerCmd.Flags().String(commonflags.AlphabetWalletsFlag, "", commonflags.AlphabetWalletsFlagDesc)
|
||||
registerCmd.Flags().String(nnsNameFlag, "", nnsNameFlagDesc)
|
||||
registerCmd.Flags().String(nnsEmailFlag, constants.FrostfsOpsEmail, "Domain owner email")
|
||||
registerCmd.Flags().Int64(nnsRefreshFlag, constants.NNSRefreshDefVal, "SOA record REFRESH parameter")
|
||||
registerCmd.Flags().Int64(nnsRetryFlag, constants.NNSRetryDefVal, "SOA record RETRY parameter")
|
||||
registerCmd.Flags().Int64(nnsExpireFlag, int64(constants.DefaultExpirationTime), "SOA record EXPIRE parameter")
|
||||
registerCmd.Flags().Int64(nnsTTLFlag, constants.NNSTtlDefVal, "SOA record TTL parameter")
|
||||
|
||||
_ = cobra.MarkFlagRequired(registerCmd.Flags(), nnsNameFlag)
|
||||
}
|
||||
|
||||
func registerDomain(cmd *cobra.Command, _ []string) {
|
||||
c, actor := nnsWriter(cmd)
|
||||
|
||||
name, _ := cmd.Flags().GetString(nnsNameFlag)
|
||||
email, _ := cmd.Flags().GetString(nnsEmailFlag)
|
||||
refresh, _ := cmd.Flags().GetInt64(nnsRefreshFlag)
|
||||
retry, _ := cmd.Flags().GetInt64(nnsRetryFlag)
|
||||
expire, _ := cmd.Flags().GetInt64(nnsExpireFlag)
|
||||
ttl, _ := cmd.Flags().GetInt64(nnsTTLFlag)
|
||||
|
||||
h, vub, err := c.Register(name, actor.Sender(), email, big.NewInt(refresh),
|
||||
big.NewInt(retry), big.NewInt(expire), big.NewInt(ttl))
|
||||
commonCmd.ExitOnErr(cmd, "unable to register domain: %w", err)
|
||||
|
||||
cmd.Println("Waiting for transaction to persist...")
|
||||
_, err = actor.Wait(h, vub, err)
|
||||
commonCmd.ExitOnErr(cmd, "register domain error: %w", err)
|
||||
cmd.Println("Domain registered successfully")
|
||||
}
|
||||
|
||||
func initDeleteCmd() {
|
||||
Cmd.AddCommand(deleteCmd)
|
||||
deleteCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
deleteCmd.Flags().String(commonflags.AlphabetWalletsFlag, "", commonflags.AlphabetWalletsFlagDesc)
|
||||
deleteCmd.Flags().String(nnsNameFlag, "", nnsNameFlagDesc)
|
||||
|
||||
_ = cobra.MarkFlagRequired(deleteCmd.Flags(), nnsNameFlag)
|
||||
}
|
||||
|
||||
func deleteDomain(cmd *cobra.Command, _ []string) {
|
||||
c, actor := nnsWriter(cmd)
|
||||
|
||||
name, _ := cmd.Flags().GetString(nnsNameFlag)
|
||||
h, vub, err := c.DeleteDomain(name)
|
||||
|
||||
_, err = actor.Wait(h, vub, err)
|
||||
commonCmd.ExitOnErr(cmd, "delete domain error: %w", err)
|
||||
cmd.Println("Domain deleted successfully")
|
||||
}
|
38
cmd/frostfs-adm/internal/modules/morph/nns/helper.go
Normal file
38
cmd/frostfs-adm/internal/modules/morph/nns/helper.go
Normal file
|
@ -0,0 +1,38 @@
|
|||
package nns
|
||||
|
||||
import (
|
||||
client "git.frostfs.info/TrueCloudLab/frostfs-contract/rpcclient/nns"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/constants"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/helper"
|
||||
commonCmd "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/internal/common"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/invoker"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/management"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
func nnsWriter(cmd *cobra.Command) (*client.Contract, *helper.LocalActor) {
|
||||
v := viper.GetViper()
|
||||
c, err := helper.NewRemoteClient(v)
|
||||
commonCmd.ExitOnErr(cmd, "unable to create NEO rpc client: %w", err)
|
||||
|
||||
ac, err := helper.NewLocalActor(cmd, c, constants.CommitteeAccountName)
|
||||
commonCmd.ExitOnErr(cmd, "can't create actor: %w", err)
|
||||
|
||||
r := management.NewReader(ac.Invoker)
|
||||
nnsCs, err := helper.GetContractByID(r, 1)
|
||||
commonCmd.ExitOnErr(cmd, "can't get NNS contract state: %w", err)
|
||||
return client.New(ac, nnsCs.Hash), ac
|
||||
}
|
||||
|
||||
func nnsReader(cmd *cobra.Command) (*client.ContractReader, *invoker.Invoker) {
|
||||
c, err := helper.NewRemoteClient(viper.GetViper())
|
||||
commonCmd.ExitOnErr(cmd, "unable to create NEO rpc client: %w", err)
|
||||
|
||||
inv := invoker.New(c, nil)
|
||||
r := management.NewReader(inv)
|
||||
nnsCs, err := helper.GetContractByID(r, 1)
|
||||
commonCmd.ExitOnErr(cmd, "can't get NNS contract state: %w", err)
|
||||
|
||||
return client.NewReader(inv, nnsCs.Hash), inv
|
||||
}
|
175
cmd/frostfs-adm/internal/modules/morph/nns/record.go
Normal file
175
cmd/frostfs-adm/internal/modules/morph/nns/record.go
Normal file
|
@ -0,0 +1,175 @@
|
|||
package nns
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"math/big"
|
||||
"strings"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-contract/nns"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
commonCmd "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/internal/common"
|
||||
"github.com/nspcc-dev/neo-go/pkg/vm/stackitem"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func initAddRecordCmd() {
|
||||
Cmd.AddCommand(addRecordCmd)
|
||||
addRecordCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
addRecordCmd.Flags().String(commonflags.AlphabetWalletsFlag, "", commonflags.AlphabetWalletsFlagDesc)
|
||||
addRecordCmd.Flags().String(nnsNameFlag, "", nnsNameFlagDesc)
|
||||
addRecordCmd.Flags().String(nnsRecordTypeFlag, "", nnsRecordTypeFlagDesc)
|
||||
addRecordCmd.Flags().String(nnsRecordDataFlag, "", nnsRecordDataFlagDesc)
|
||||
|
||||
_ = cobra.MarkFlagRequired(addRecordCmd.Flags(), nnsNameFlag)
|
||||
_ = cobra.MarkFlagRequired(addRecordCmd.Flags(), nnsRecordTypeFlag)
|
||||
_ = cobra.MarkFlagRequired(addRecordCmd.Flags(), nnsRecordDataFlag)
|
||||
}
|
||||
|
||||
func initGetRecordsCmd() {
|
||||
Cmd.AddCommand(getRecordsCmd)
|
||||
getRecordsCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
getRecordsCmd.Flags().String(nnsNameFlag, "", nnsNameFlagDesc)
|
||||
getRecordsCmd.Flags().String(nnsRecordTypeFlag, "", nnsRecordTypeFlagDesc)
|
||||
|
||||
_ = cobra.MarkFlagRequired(getRecordsCmd.Flags(), nnsNameFlag)
|
||||
}
|
||||
|
||||
func initDelRecordsCmd() {
|
||||
Cmd.AddCommand(delRecordsCmd)
|
||||
delRecordsCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
delRecordsCmd.Flags().String(commonflags.AlphabetWalletsFlag, "", commonflags.AlphabetWalletsFlagDesc)
|
||||
delRecordsCmd.Flags().String(nnsNameFlag, "", nnsNameFlagDesc)
|
||||
delRecordsCmd.Flags().String(nnsRecordTypeFlag, "", nnsRecordTypeFlagDesc)
|
||||
|
||||
_ = cobra.MarkFlagRequired(delRecordsCmd.Flags(), nnsNameFlag)
|
||||
_ = cobra.MarkFlagRequired(delRecordsCmd.Flags(), nnsRecordTypeFlag)
|
||||
}
|
||||
|
||||
func initDelRecordCmd() {
|
||||
Cmd.AddCommand(delRecordCmd)
|
||||
delRecordCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
delRecordCmd.Flags().String(commonflags.AlphabetWalletsFlag, "", commonflags.AlphabetWalletsFlagDesc)
|
||||
delRecordCmd.Flags().String(nnsNameFlag, "", nnsNameFlagDesc)
|
||||
delRecordCmd.Flags().String(nnsRecordTypeFlag, "", nnsRecordTypeFlagDesc)
|
||||
delRecordCmd.Flags().String(nnsRecordDataFlag, "", nnsRecordDataFlagDesc)
|
||||
|
||||
_ = cobra.MarkFlagRequired(delRecordCmd.Flags(), nnsNameFlag)
|
||||
_ = cobra.MarkFlagRequired(delRecordCmd.Flags(), nnsRecordTypeFlag)
|
||||
_ = cobra.MarkFlagRequired(delRecordCmd.Flags(), nnsRecordDataFlag)
|
||||
}
|
||||
|
||||
func addRecord(cmd *cobra.Command, _ []string) {
|
||||
c, actor := nnsWriter(cmd)
|
||||
name, _ := cmd.Flags().GetString(nnsNameFlag)
|
||||
data, _ := cmd.Flags().GetString(nnsRecordDataFlag)
|
||||
recordType, _ := cmd.Flags().GetString(nnsRecordTypeFlag)
|
||||
typ, err := getRecordType(recordType)
|
||||
commonCmd.ExitOnErr(cmd, "unable to parse record type: %w", err)
|
||||
h, vub, err := c.AddRecord(name, typ, data)
|
||||
commonCmd.ExitOnErr(cmd, "unable to add record: %w", err)
|
||||
|
||||
cmd.Println("Waiting for transaction to persist...")
|
||||
_, err = actor.Wait(h, vub, err)
|
||||
commonCmd.ExitOnErr(cmd, "renew domain error: %w", err)
|
||||
cmd.Println("Record added successfully")
|
||||
}
|
||||
|
||||
func getRecords(cmd *cobra.Command, _ []string) {
|
||||
c, inv := nnsReader(cmd)
|
||||
name, _ := cmd.Flags().GetString(nnsNameFlag)
|
||||
recordType, _ := cmd.Flags().GetString(nnsRecordTypeFlag)
|
||||
if recordType == "" {
|
||||
sid, r, err := c.GetAllRecords(name)
|
||||
commonCmd.ExitOnErr(cmd, "unable to get records: %w", err)
|
||||
defer func() {
|
||||
_ = inv.TerminateSession(sid)
|
||||
}()
|
||||
items, err := inv.TraverseIterator(sid, &r, 0)
|
||||
commonCmd.ExitOnErr(cmd, "unable to get records: %w", err)
|
||||
for len(items) != 0 {
|
||||
for j := range items {
|
||||
rs := items[j].Value().([]stackitem.Item)
|
||||
bs, err := rs[2].TryBytes()
|
||||
commonCmd.ExitOnErr(cmd, "unable to parse record state: %w", err)
|
||||
cmd.Printf("%s %s\n",
|
||||
recordTypeToString(nns.RecordType(rs[1].Value().(*big.Int).Int64())),
|
||||
string(bs))
|
||||
}
|
||||
items, err = inv.TraverseIterator(sid, &r, 0)
|
||||
commonCmd.ExitOnErr(cmd, "unable to get records: %w", err)
|
||||
}
|
||||
} else {
|
||||
typ, err := getRecordType(recordType)
|
||||
commonCmd.ExitOnErr(cmd, "unable to parse record type: %w", err)
|
||||
items, err := c.GetRecords(name, typ)
|
||||
commonCmd.ExitOnErr(cmd, "unable to get records: %w", err)
|
||||
for _, item := range items {
|
||||
record, err := item.TryBytes()
|
||||
commonCmd.ExitOnErr(cmd, "unable to parse response: %w", err)
|
||||
cmd.Println(string(record))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func delRecords(cmd *cobra.Command, _ []string) {
|
||||
c, actor := nnsWriter(cmd)
|
||||
name, _ := cmd.Flags().GetString(nnsNameFlag)
|
||||
recordType, _ := cmd.Flags().GetString(nnsRecordTypeFlag)
|
||||
typ, err := getRecordType(recordType)
|
||||
commonCmd.ExitOnErr(cmd, "unable to parse record type: %w", err)
|
||||
h, vub, err := c.DeleteRecords(name, typ)
|
||||
commonCmd.ExitOnErr(cmd, "unable to delete records: %w", err)
|
||||
|
||||
cmd.Println("Waiting for transaction to persist...")
|
||||
_, err = actor.Wait(h, vub, err)
|
||||
commonCmd.ExitOnErr(cmd, "delete records error: %w", err)
|
||||
cmd.Println("Records removed successfully")
|
||||
}
|
||||
|
||||
func delRecord(cmd *cobra.Command, _ []string) {
|
||||
c, actor := nnsWriter(cmd)
|
||||
name, _ := cmd.Flags().GetString(nnsNameFlag)
|
||||
data, _ := cmd.Flags().GetString(nnsRecordDataFlag)
|
||||
recordType, _ := cmd.Flags().GetString(nnsRecordTypeFlag)
|
||||
typ, err := getRecordType(recordType)
|
||||
commonCmd.ExitOnErr(cmd, "unable to parse record type: %w", err)
|
||||
h, vub, err := c.DeleteRecord(name, typ, data)
|
||||
commonCmd.ExitOnErr(cmd, "unable to delete record: %w", err)
|
||||
|
||||
cmd.Println("Waiting for transaction to persist...")
|
||||
_, err = actor.Wait(h, vub, err)
|
||||
commonCmd.ExitOnErr(cmd, "delete records error: %w", err)
|
||||
cmd.Println("Record removed successfully")
|
||||
}
|
||||
|
||||
func getRecordType(recordType string) (*big.Int, error) {
|
||||
switch strings.ToUpper(recordType) {
|
||||
case "A":
|
||||
return big.NewInt(int64(nns.A)), nil
|
||||
case "CNAME":
|
||||
return big.NewInt(int64(nns.CNAME)), nil
|
||||
case "SOA":
|
||||
return big.NewInt(int64(nns.SOA)), nil
|
||||
case "TXT":
|
||||
return big.NewInt(int64(nns.TXT)), nil
|
||||
case "AAAA":
|
||||
return big.NewInt(int64(nns.AAAA)), nil
|
||||
}
|
||||
return nil, errors.New("unsupported record type")
|
||||
}
|
||||
|
||||
func recordTypeToString(rt nns.RecordType) string {
|
||||
switch rt {
|
||||
case nns.A:
|
||||
return "A"
|
||||
case nns.CNAME:
|
||||
return "CNAME"
|
||||
case nns.SOA:
|
||||
return "SOA"
|
||||
case nns.TXT:
|
||||
return "TXT"
|
||||
case nns.AAAA:
|
||||
return "AAAA"
|
||||
}
|
||||
return ""
|
||||
}
|
26
cmd/frostfs-adm/internal/modules/morph/nns/renew.go
Normal file
26
cmd/frostfs-adm/internal/modules/morph/nns/renew.go
Normal file
|
@ -0,0 +1,26 @@
|
|||
package nns
|
||||
|
||||
import (
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
commonCmd "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/internal/common"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func initRenewCmd() {
|
||||
Cmd.AddCommand(renewCmd)
|
||||
renewCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
renewCmd.Flags().String(commonflags.AlphabetWalletsFlag, "", commonflags.AlphabetWalletsFlagDesc)
|
||||
renewCmd.Flags().String(nnsNameFlag, "", nnsNameFlagDesc)
|
||||
}
|
||||
|
||||
func renewDomain(cmd *cobra.Command, _ []string) {
|
||||
c, actor := nnsWriter(cmd)
|
||||
name, _ := cmd.Flags().GetString(nnsNameFlag)
|
||||
h, vub, err := c.Renew(name)
|
||||
commonCmd.ExitOnErr(cmd, "unable to renew domain: %w", err)
|
||||
|
||||
cmd.Println("Waiting for transaction to persist...")
|
||||
_, err = actor.Wait(h, vub, err)
|
||||
commonCmd.ExitOnErr(cmd, "renew domain error: %w", err)
|
||||
cmd.Println("Domain renewed successfully")
|
||||
}
|
119
cmd/frostfs-adm/internal/modules/morph/nns/root.go
Normal file
119
cmd/frostfs-adm/internal/modules/morph/nns/root.go
Normal file
|
@ -0,0 +1,119 @@
|
|||
package nns
|
||||
|
||||
import (
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
const (
|
||||
nnsNameFlag = "name"
|
||||
nnsNameFlagDesc = "Domain name"
|
||||
nnsEmailFlag = "email"
|
||||
nnsRefreshFlag = "refresh"
|
||||
nnsRetryFlag = "retry"
|
||||
nnsExpireFlag = "expire"
|
||||
nnsTTLFlag = "ttl"
|
||||
nnsRecordTypeFlag = "type"
|
||||
nnsRecordTypeFlagDesc = "Domain name service record type(A|CNAME|SOA|TXT)"
|
||||
nnsRecordDataFlag = "data"
|
||||
nnsRecordDataFlagDesc = "Domain name service record data"
|
||||
)
|
||||
|
||||
var (
|
||||
Cmd = &cobra.Command{
|
||||
Use: "nns",
|
||||
Short: "Section for Neo Name Service (NNS)",
|
||||
}
|
||||
tokensCmd = &cobra.Command{
|
||||
Use: "tokens",
|
||||
Short: "List all registered domain names",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
Run: listTokens,
|
||||
}
|
||||
registerCmd = &cobra.Command{
|
||||
Use: "register",
|
||||
Short: "Registers a new domain",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
_ = viper.BindPFlag(commonflags.AlphabetWalletsFlag, cmd.Flags().Lookup(commonflags.AlphabetWalletsFlag))
|
||||
},
|
||||
Run: registerDomain,
|
||||
}
|
||||
deleteCmd = &cobra.Command{
|
||||
Use: "delete",
|
||||
Short: "Delete a domain by name",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
_ = viper.BindPFlag(commonflags.AlphabetWalletsFlag, cmd.Flags().Lookup(commonflags.AlphabetWalletsFlag))
|
||||
},
|
||||
Run: deleteDomain,
|
||||
}
|
||||
renewCmd = &cobra.Command{
|
||||
Use: "renew",
|
||||
Short: "Increases domain expiration date",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
_ = viper.BindPFlag(commonflags.AlphabetWalletsFlag, cmd.Flags().Lookup(commonflags.AlphabetWalletsFlag))
|
||||
},
|
||||
Run: renewDomain,
|
||||
}
|
||||
updateCmd = &cobra.Command{
|
||||
Use: "update",
|
||||
Short: "Updates soa record",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
_ = viper.BindPFlag(commonflags.AlphabetWalletsFlag, cmd.Flags().Lookup(commonflags.AlphabetWalletsFlag))
|
||||
},
|
||||
Run: updateSOA,
|
||||
}
|
||||
addRecordCmd = &cobra.Command{
|
||||
Use: "add-record",
|
||||
Short: "Adds a new record of the specified type to the provided domain",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
_ = viper.BindPFlag(commonflags.AlphabetWalletsFlag, cmd.Flags().Lookup(commonflags.AlphabetWalletsFlag))
|
||||
},
|
||||
Run: addRecord,
|
||||
}
|
||||
getRecordsCmd = &cobra.Command{
|
||||
Use: "get-records",
|
||||
Short: "Returns domain record of the specified type",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
Run: getRecords,
|
||||
}
|
||||
delRecordsCmd = &cobra.Command{
|
||||
Use: "delete-records",
|
||||
Short: "Removes domain records with the specified type",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
_ = viper.BindPFlag(commonflags.AlphabetWalletsFlag, cmd.Flags().Lookup(commonflags.AlphabetWalletsFlag))
|
||||
},
|
||||
Run: delRecords,
|
||||
}
|
||||
delRecordCmd = &cobra.Command{
|
||||
Use: "delete-record",
|
||||
Short: "Removes domain record with the specified type and data",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
_ = viper.BindPFlag(commonflags.AlphabetWalletsFlag, cmd.Flags().Lookup(commonflags.AlphabetWalletsFlag))
|
||||
},
|
||||
Run: delRecord,
|
||||
}
|
||||
)
|
||||
|
||||
func init() {
|
||||
initTokensCmd()
|
||||
initRegisterCmd()
|
||||
initDeleteCmd()
|
||||
initRenewCmd()
|
||||
initUpdateCmd()
|
||||
initAddRecordCmd()
|
||||
initGetRecordsCmd()
|
||||
initDelRecordsCmd()
|
||||
initDelRecordCmd()
|
||||
}
|
65
cmd/frostfs-adm/internal/modules/morph/nns/tokens.go
Normal file
65
cmd/frostfs-adm/internal/modules/morph/nns/tokens.go
Normal file
|
@ -0,0 +1,65 @@
|
|||
package nns
|
||||
|
||||
import (
|
||||
"math/big"
|
||||
"strings"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-contract/nns"
|
||||
client "git.frostfs.info/TrueCloudLab/frostfs-contract/rpcclient/nns"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
commonCmd "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/internal/common"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
const (
|
||||
verboseDesc = "Include additional information about CNAME record."
|
||||
)
|
||||
|
||||
func initTokensCmd() {
|
||||
Cmd.AddCommand(tokensCmd)
|
||||
tokensCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
tokensCmd.Flags().BoolP(commonflags.Verbose, commonflags.VerboseShorthand, false, verboseDesc)
|
||||
}
|
||||
|
||||
func listTokens(cmd *cobra.Command, _ []string) {
|
||||
c, _ := nnsReader(cmd)
|
||||
it, err := c.Tokens()
|
||||
commonCmd.ExitOnErr(cmd, "unable to get tokens: %w", err)
|
||||
for toks, err := it.Next(10); err == nil && len(toks) > 0; toks, err = it.Next(10) {
|
||||
for _, token := range toks {
|
||||
output := string(token)
|
||||
if verbose, _ := cmd.Flags().GetBool(commonflags.Verbose); verbose {
|
||||
cname, err := getCnameRecord(c, token)
|
||||
commonCmd.ExitOnErr(cmd, "", err)
|
||||
if cname != "" {
|
||||
output += " (CNAME: " + cname + ")"
|
||||
}
|
||||
}
|
||||
cmd.Println(output)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func getCnameRecord(c *client.ContractReader, token []byte) (string, error) {
|
||||
items, err := c.GetRecords(string(token), big.NewInt(int64(nns.CNAME)))
|
||||
|
||||
// GetRecords returns the error "not an array" if the domain does not contain records.
|
||||
if err != nil && strings.Contains(err.Error(), "not an array") {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if len(items) == 0 {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
record, err := items[0].TryBytes()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return string(record), nil
|
||||
}
|
50
cmd/frostfs-adm/internal/modules/morph/nns/update.go
Normal file
50
cmd/frostfs-adm/internal/modules/morph/nns/update.go
Normal file
|
@ -0,0 +1,50 @@
|
|||
package nns
|
||||
|
||||
import (
|
||||
"math/big"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/constants"
|
||||
commonCmd "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/internal/common"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func initUpdateCmd() {
|
||||
Cmd.AddCommand(updateCmd)
|
||||
updateCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
updateCmd.Flags().String(commonflags.AlphabetWalletsFlag, "", commonflags.AlphabetWalletsFlagDesc)
|
||||
updateCmd.Flags().String(nnsNameFlag, "", nnsNameFlagDesc)
|
||||
updateCmd.Flags().String(nnsEmailFlag, constants.FrostfsOpsEmail, "Domain owner email")
|
||||
updateCmd.Flags().Int64(nnsRefreshFlag, constants.NNSRefreshDefVal,
|
||||
"The number of seconds between update requests from secondary and slave name servers")
|
||||
updateCmd.Flags().Int64(nnsRetryFlag, constants.NNSRetryDefVal,
|
||||
"The number of seconds the secondary or slave will wait before retrying when the last attempt has failed")
|
||||
updateCmd.Flags().Int64(nnsExpireFlag, int64(constants.DefaultExpirationTime),
|
||||
"The number of seconds a master or slave will wait before considering the data stale "+
|
||||
"if it cannot reach the primary name server")
|
||||
updateCmd.Flags().Int64(nnsTTLFlag, constants.NNSTtlDefVal,
|
||||
"The number of seconds a domain name is cached locally before expiration and return to authoritative "+
|
||||
"nameservers for updated information")
|
||||
|
||||
_ = cobra.MarkFlagRequired(updateCmd.Flags(), nnsNameFlag)
|
||||
}
|
||||
|
||||
func updateSOA(cmd *cobra.Command, _ []string) {
|
||||
c, actor := nnsWriter(cmd)
|
||||
|
||||
name, _ := cmd.Flags().GetString(nnsNameFlag)
|
||||
email, _ := cmd.Flags().GetString(nnsEmailFlag)
|
||||
refresh, _ := cmd.Flags().GetInt64(nnsRefreshFlag)
|
||||
retry, _ := cmd.Flags().GetInt64(nnsRetryFlag)
|
||||
expire, _ := cmd.Flags().GetInt64(nnsExpireFlag)
|
||||
ttl, _ := cmd.Flags().GetInt64(nnsTTLFlag)
|
||||
|
||||
h, vub, err := c.UpdateSOA(name, email, big.NewInt(refresh),
|
||||
big.NewInt(retry), big.NewInt(expire), big.NewInt(ttl))
|
||||
commonCmd.ExitOnErr(cmd, "unable to send transaction: %w", err)
|
||||
|
||||
cmd.Println("Waiting for transaction to persist...")
|
||||
_, err = actor.Wait(h, vub, err)
|
||||
commonCmd.ExitOnErr(cmd, "register domain error: %w", err)
|
||||
cmd.Println("SOA records updated successfully")
|
||||
}
|
|
@ -1,10 +1,12 @@
|
|||
package morph
|
||||
package node
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
netmapcontract "git.frostfs.info/TrueCloudLab/frostfs-contract/netmap"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/constants"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/helper"
|
||||
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
|
||||
"github.com/nspcc-dev/neo-go/pkg/io"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/management"
|
||||
|
@ -14,7 +16,7 @@ import (
|
|||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
func removeNodesCmd(cmd *cobra.Command, args []string) error {
|
||||
func RemoveNodesCmd(cmd *cobra.Command, args []string) error {
|
||||
if len(args) == 0 {
|
||||
return errors.New("at least one node key must be provided")
|
||||
}
|
||||
|
@ -28,19 +30,19 @@ func removeNodesCmd(cmd *cobra.Command, args []string) error {
|
|||
}
|
||||
}
|
||||
|
||||
wCtx, err := newInitializeContext(cmd, viper.GetViper())
|
||||
wCtx, err := helper.NewInitializeContext(cmd, viper.GetViper())
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't initialize context: %w", err)
|
||||
}
|
||||
defer wCtx.close()
|
||||
defer wCtx.Close()
|
||||
|
||||
r := management.NewReader(wCtx.ReadOnlyInvoker)
|
||||
cs, err := r.GetContractByID(1)
|
||||
cs, err := helper.GetContractByID(r, 1)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't get NNS contract info: %w", err)
|
||||
}
|
||||
|
||||
nmHash, err := nnsResolveHash(wCtx.ReadOnlyInvoker, cs.Hash, domainOf(netmapContract))
|
||||
nmHash, err := helper.NNSResolveHash(wCtx.ReadOnlyInvoker, cs.Hash, helper.DomainOf(constants.NetmapContract))
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't get netmap contract hash: %w", err)
|
||||
}
|
||||
|
@ -51,13 +53,13 @@ func removeNodesCmd(cmd *cobra.Command, args []string) error {
|
|||
int64(netmapcontract.NodeStateOffline), nodeKeys[i].Bytes())
|
||||
}
|
||||
|
||||
if err := emitNewEpochCall(bw, wCtx, nmHash); err != nil {
|
||||
if err := helper.EmitNewEpochCall(bw, wCtx, nmHash, 1); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := wCtx.sendConsensusTx(bw.Bytes()); err != nil {
|
||||
if err := wCtx.SendConsensusTx(bw.Bytes()); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return wCtx.awaitTx()
|
||||
return wCtx.AwaitTx()
|
||||
}
|
28
cmd/frostfs-adm/internal/modules/morph/node/root.go
Normal file
28
cmd/frostfs-adm/internal/modules/morph/node/root.go
Normal file
|
@ -0,0 +1,28 @@
|
|||
package node
|
||||
|
||||
import (
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var RemoveCmd = &cobra.Command{
|
||||
Use: "remove-nodes key1 [key2 [...]]",
|
||||
Short: "Remove storage nodes from the netmap",
|
||||
Long: `Move nodes to the Offline state in the candidates list and tick an epoch to update the netmap`,
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.AlphabetWalletsFlag, cmd.Flags().Lookup(commonflags.AlphabetWalletsFlag))
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
RunE: RemoveNodesCmd,
|
||||
}
|
||||
|
||||
func initRemoveNodesCmd() {
|
||||
RemoveCmd.Flags().String(commonflags.AlphabetWalletsFlag, "", commonflags.AlphabetWalletsFlagDesc)
|
||||
RemoveCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
RemoveCmd.Flags().String(commonflags.LocalDumpFlag, "", "Path to the blocks dump file")
|
||||
}
|
||||
|
||||
func init() {
|
||||
initRemoveNodesCmd()
|
||||
}
|
|
@ -1,10 +1,12 @@
|
|||
package morph
|
||||
package notary
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"strconv"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/helper"
|
||||
"github.com/nspcc-dev/neo-go/cli/input"
|
||||
"github.com/nspcc-dev/neo-go/pkg/core/transaction"
|
||||
"github.com/nspcc-dev/neo-go/pkg/crypto/keys"
|
||||
|
@ -20,9 +22,16 @@ import (
|
|||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
// defaultNotaryDepositLifetime is an amount of blocks notary deposit stays valid.
|
||||
// https://github.com/nspcc-dev/neo-go/blob/master/pkg/core/native/notary.go#L48
|
||||
const defaultNotaryDepositLifetime = 5760
|
||||
const (
|
||||
// defaultNotaryDepositLifetime is an amount of blocks notary deposit stays valid.
|
||||
// https://github.com/nspcc-dev/neo-go/blob/master/pkg/core/native/notary.go#L48
|
||||
defaultNotaryDepositLifetime = 5760
|
||||
|
||||
walletAccountFlag = "account"
|
||||
notaryDepositTillFlag = "till"
|
||||
)
|
||||
|
||||
var errInvalidNotaryDepositLifetime = errors.New("notary deposit lifetime must be a positive integer")
|
||||
|
||||
func depositNotary(cmd *cobra.Command, _ []string) error {
|
||||
w, err := openWallet(cmd)
|
||||
|
@ -31,7 +40,8 @@ func depositNotary(cmd *cobra.Command, _ []string) error {
|
|||
}
|
||||
|
||||
accHash := w.GetChangeAddress()
|
||||
if addr, err := cmd.Flags().GetString(walletAccountFlag); err == nil {
|
||||
addr, _ := cmd.Flags().GetString(walletAccountFlag)
|
||||
if addr != "" {
|
||||
accHash, err = address.StringToUint160(addr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid address: %s", addr)
|
||||
|
@ -43,7 +53,7 @@ func depositNotary(cmd *cobra.Command, _ []string) error {
|
|||
return fmt.Errorf("can't find account for %s", accHash)
|
||||
}
|
||||
|
||||
prompt := fmt.Sprintf("Enter password for %s >", address.Uint160ToString(accHash))
|
||||
prompt := fmt.Sprintf("Enter password for %s > ", address.Uint160ToString(accHash))
|
||||
pass, err := input.ReadPassword(prompt)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't get password: %v", err)
|
||||
|
@ -54,37 +64,30 @@ func depositNotary(cmd *cobra.Command, _ []string) error {
|
|||
return fmt.Errorf("can't unlock account: %v", err)
|
||||
}
|
||||
|
||||
gasStr, err := cmd.Flags().GetString(refillGasAmountFlag)
|
||||
gasStr, err := cmd.Flags().GetString(commonflags.RefillGasAmountFlag)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
gasAmount, err := parseGASAmount(gasStr)
|
||||
gasAmount, err := helper.ParseGASAmount(gasStr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
till := int64(defaultNotaryDepositLifetime)
|
||||
tillStr, err := cmd.Flags().GetString(notaryDepositTillFlag)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tillStr != "" {
|
||||
till, err = strconv.ParseInt(tillStr, 10, 64)
|
||||
if err != nil || till <= 0 {
|
||||
return fmt.Errorf("notary deposit lifetime must be a positive integer")
|
||||
}
|
||||
till, _ := cmd.Flags().GetInt64(notaryDepositTillFlag)
|
||||
if till <= 0 {
|
||||
return errInvalidNotaryDepositLifetime
|
||||
}
|
||||
|
||||
return transferGas(cmd, acc, accHash, gasAmount, till)
|
||||
}
|
||||
|
||||
func transferGas(cmd *cobra.Command, acc *wallet.Account, accHash util.Uint160, gasAmount fixedn.Fixed8, till int64) error {
|
||||
c, err := getN3Client(viper.GetViper())
|
||||
c, err := helper.NewRemoteClient(viper.GetViper())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := checkNotaryEnabled(c); err != nil {
|
||||
if err := helper.CheckNotaryEnabled(c); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
|
@ -116,15 +119,15 @@ func transferGas(cmd *cobra.Command, acc *wallet.Account, accHash util.Uint160,
|
|||
return fmt.Errorf("could not send tx: %w", err)
|
||||
}
|
||||
|
||||
return awaitTx(cmd, c, []hashVUBPair{{hash: txHash, vub: vub}})
|
||||
return helper.AwaitTx(cmd, c, []helper.HashVUBPair{{Hash: txHash, Vub: vub}})
|
||||
}
|
||||
|
||||
func openWallet(cmd *cobra.Command) (*wallet.Wallet, error) {
|
||||
p, err := cmd.Flags().GetString(storageWalletFlag)
|
||||
p, err := cmd.Flags().GetString(commonflags.StorageWalletFlag)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
} else if p == "" {
|
||||
return nil, fmt.Errorf("missing wallet path (use '--%s <out.json>')", storageWalletFlag)
|
||||
return nil, fmt.Errorf("missing wallet path (use '--%s <out.json>')", commonflags.StorageWalletFlag)
|
||||
}
|
||||
|
||||
w, err := wallet.NewWalletFromFile(p)
|
28
cmd/frostfs-adm/internal/modules/morph/notary/root.go
Normal file
28
cmd/frostfs-adm/internal/modules/morph/notary/root.go
Normal file
|
@ -0,0 +1,28 @@
|
|||
package notary
|
||||
|
||||
import (
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var DepositCmd = &cobra.Command{
|
||||
Use: "deposit-notary",
|
||||
Short: "Deposit GAS for notary service",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
RunE: depositNotary,
|
||||
}
|
||||
|
||||
func initDepositoryNotaryCmd() {
|
||||
DepositCmd.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
DepositCmd.Flags().String(commonflags.StorageWalletFlag, "", "Path to storage node wallet")
|
||||
DepositCmd.Flags().String(walletAccountFlag, "", "Wallet account address")
|
||||
DepositCmd.Flags().String(commonflags.RefillGasAmountFlag, "", "Amount of GAS to deposit")
|
||||
DepositCmd.Flags().Int64(notaryDepositTillFlag, defaultNotaryDepositLifetime, "Notary deposit duration in blocks")
|
||||
}
|
||||
|
||||
func init() {
|
||||
initDepositoryNotaryCmd()
|
||||
}
|
|
@ -1,12 +1,14 @@
|
|||
package morph
|
||||
package policy
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"text/tabwriter"
|
||||
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/modules/morph/helper"
|
||||
commonCmd "git.frostfs.info/TrueCloudLab/frostfs-node/cmd/internal/common"
|
||||
"github.com/nspcc-dev/neo-go/pkg/io"
|
||||
"github.com/nspcc-dev/neo-go/pkg/rpcclient/invoker"
|
||||
|
@ -23,17 +25,19 @@ const (
|
|||
setFeeParam = "FeePerByte"
|
||||
)
|
||||
|
||||
func setPolicyCmd(cmd *cobra.Command, args []string) error {
|
||||
wCtx, err := newInitializeContext(cmd, viper.GetViper())
|
||||
var errInvalidParameterFormat = errors.New("invalid parameter format, must be Parameter=Value")
|
||||
|
||||
func SetPolicyCmd(cmd *cobra.Command, args []string) error {
|
||||
wCtx, err := helper.NewInitializeContext(cmd, viper.GetViper())
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't to initialize context: %w", err)
|
||||
return fmt.Errorf("can't initialize context: %w", err)
|
||||
}
|
||||
|
||||
bw := io.NewBufBinWriter()
|
||||
for i := range args {
|
||||
k, v, found := strings.Cut(args[i], "=")
|
||||
if !found {
|
||||
return fmt.Errorf("invalid parameter format, must be Parameter=Value")
|
||||
return errInvalidParameterFormat
|
||||
}
|
||||
|
||||
switch k {
|
||||
|
@ -44,21 +48,21 @@ func setPolicyCmd(cmd *cobra.Command, args []string) error {
|
|||
|
||||
value, err := strconv.ParseUint(v, 10, 32)
|
||||
if err != nil {
|
||||
return fmt.Errorf("can't parse parameter value '%s': %w", args[1], err)
|
||||
return fmt.Errorf("can't parse parameter value '%s': %w", args[i], err)
|
||||
}
|
||||
|
||||
emit.AppCall(bw.BinWriter, policy.Hash, "set"+k, callflag.All, int64(value))
|
||||
}
|
||||
|
||||
if err := wCtx.sendCommitteeTx(bw.Bytes(), false); err != nil {
|
||||
if err := wCtx.SendCommitteeTx(bw.Bytes(), false); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return wCtx.awaitTx()
|
||||
return wCtx.AwaitTx()
|
||||
}
|
||||
|
||||
func dumpPolicyCmd(cmd *cobra.Command, _ []string) error {
|
||||
c, err := getN3Client(viper.GetViper())
|
||||
c, err := helper.NewRemoteClient(viper.GetViper())
|
||||
commonCmd.ExitOnErr(cmd, "can't create N3 client:", err)
|
||||
|
||||
inv := invoker.New(c, nil)
|
47
cmd/frostfs-adm/internal/modules/morph/policy/root.go
Normal file
47
cmd/frostfs-adm/internal/modules/morph/policy/root.go
Normal file
|
@ -0,0 +1,47 @@
|
|||
package policy
|
||||
|
||||
import (
|
||||
"git.frostfs.info/TrueCloudLab/frostfs-node/cmd/frostfs-adm/internal/commonflags"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var (
|
||||
Set = &cobra.Command{
|
||||
Use: "set-policy [ExecFeeFactor=<n1>] [StoragePrice=<n2>] [FeePerByte=<n3>]",
|
||||
DisableFlagsInUseLine: true,
|
||||
Short: "Set global policy values",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.AlphabetWalletsFlag, cmd.Flags().Lookup(commonflags.AlphabetWalletsFlag))
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
RunE: SetPolicyCmd,
|
||||
ValidArgsFunction: func(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
|
||||
return []string{"ExecFeeFactor=", "StoragePrice=", "FeePerByte="}, cobra.ShellCompDirectiveNoSpace
|
||||
},
|
||||
}
|
||||
|
||||
Dump = &cobra.Command{
|
||||
Use: "dump-policy",
|
||||
Short: "Dump FrostFS policy",
|
||||
PreRun: func(cmd *cobra.Command, _ []string) {
|
||||
_ = viper.BindPFlag(commonflags.EndpointFlag, cmd.Flags().Lookup(commonflags.EndpointFlag))
|
||||
},
|
||||
RunE: dumpPolicyCmd,
|
||||
}
|
||||
)
|
||||
|
||||
func initSetPolicyCmd() {
|
||||
Set.Flags().String(commonflags.AlphabetWalletsFlag, "", commonflags.AlphabetWalletsFlagDesc)
|
||||
Set.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
Set.Flags().String(commonflags.LocalDumpFlag, "", "Path to the blocks dump file")
|
||||
}
|
||||
|
||||
func initDumpPolicyCmd() {
|
||||
Dump.Flags().StringP(commonflags.EndpointFlag, commonflags.EndpointFlagShort, "", commonflags.EndpointFlagDesc)
|
||||
}
|
||||
|
||||
func init() {
|
||||
initSetPolicyCmd()
|
||||
initDumpPolicyCmd()
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue