-
Notifications
You must be signed in to change notification settings - Fork 7
/
cvm.clj
940 lines (500 loc) · 19.3 KB
/
cvm.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
(ns convex.cvm
"Code execution in the Convex Virtual Machine
Altering its state and gaining insights.
The central entity of this namespace is the execution context created by [[ctx]]. They embed a [[state]] and allow
executing code to alter it.
All other functions revolve around contextes. While the design of a context is mostly immutable, whenever an altering function
is applied (eg. [[juice-set]]) or code is handled in any way (eg. [[eval]]), the old context must be discarded and only the
returned one should be used.
Cheap copies can be created using [[fork]].
Actions involving code (eg. [[compile]], [[exec]], ...) return a new context which holds either a [[result]] or an [[exception]].
Those actions always consume [[juice]].
Given that a \"cell\" is the term reserved for CVM data and objects, execution consists of the following steps:
| Step | Function | Does |
|------|-------------|-----------------------------------------------------|
| 1 | [[expand]] | `cell` -> `canonical cell`, applies macros |
| 2 | [[compile]] | `canonical cell` -> `op`, preparing executable code |
| 3 | [[exec]] | Executes compiled code |
Any cell can be applied safely to those functions, worse that can happen is nothing (e.g. providing an already compiled cell to
[[compile]]).
If fine-grained control is not needed and if source is not compiled anyways, a simpler alternative is to use [[eval]] which does
all the job."
{:author "Adam Helinski"}
(:import (convex.core Block
State)
(convex.core.data ABlobMap
AccountKey
AccountStatus
ACell
Address
AHashMap)
(convex.core.data.prim CVMLong)
(convex.core.init Init)
(convex.core.lang AFn
AOp
Context)
(convex.core.lang.impl AExceptional
ErrorValue)
(convex.core.transactions ATransaction))
(:refer-clojure :exclude [compile
def
eval
key
time])
(:require [convex.cell :as $.cell]
[convex.std :as $.std]))
(set! *warn-on-reflection*
true)
(declare juice
juice-limit
juice-limit-set
juice-set
state-set)
;;;;;;;;;; Values
(def genesis-user
"Address of the first genesis user.
More precisely, when the CVM [[state]] is created in [[ctx]].
This behavior might change in the future.
It receives half of the funds reserved for all users in the state."
Init/GENESIS_ADDRESS)
;;;;;;;;;; Creating a new context
(defn ctx
"Creates an execution context.
An optional map of options may be provided:
| Key | Value | Default |
|----------------------------|--------------------------------------------------------|----------------------------------------------------|
| `:convex.cvm/address` | Address of the executing account | [[genesis-user]] |
| `:convex.cvm/genesis-key+` | Vector of public keys for genesis users (at least one) | Vector with only [[fake-key]] for [[genesis-user]] |
| `:convex.cvm/state` | State (see [[state]]) | Initial state with Convex actors and libraries |
When no state is provided, based on the provided public keys (which MUST be distinct):
- A special genesis user is created with 50% of available user funds, associated with the first public key
- For the address of that special genesis user, see [[genesis-user]]
- For each public key, an additional user is created, sharing the remaining user funds equally
- Each additional user becomes the controller of a declared peers (see the `:peers` key in the state)
- Each peer uses the same public key as its controller
- Each user stakes 1 / 3 of its balance on its peer
See [[convex.cell/key]] about creating public keys or the `convex.key-pair` namespace from `:module/net`."
(^Context []
(ctx nil))
(^Context [option+]
(Context/createFake (or (:convex.cvm/state option+)
(Init/createState (or (:convex.cvm/genesis-key+ option+)
[$.cell/key-fake])))
(or (:convex.cvm/address option+)
genesis-user))))
(defn fork
"Duplicates the given `ctx` (very cheap).
Any operation on the returned copy has no impact on the original context.
Attention, forking a [[ctx]] looses any attached [[result]] or [[exception]]."
^Context
[^Context ctx]
(.fork ctx))
(defn fork-to
"Duplicates the given `ctx` and switches the executing account.
Like [[fork]] but only [[state]] and [[juice]] are preservered.
Everything else is lost: local bindings, CVM log. CVM depth, etc."
^Context
[^Context ctx address]
(-> ctx
(.forkWithAddress address)
(juice-limit-set (juice-limit ctx))
(juice-set (juice ctx))))
;;;;;;;;;; Querying context properties
(defn- -wrap-address
;; Wraps `x` in an Address object if it is not already.
^Address
[x]
(cond->
x
(number? x)
$.cell/address))
(defn account
"Returns the account for the given `address` (or the address associated with `ctx`)."
(^AccountStatus [^Context ctx]
(.getAccountStatus ctx))
(^AccountStatus [^Context ctx address]
(.getAccountStatus ctx
(-wrap-address address))))
(defn actor?
"Returns `true` if the given address point to an actor in `ctx`.
An actor is an account without a public key."
[ctx address]
(some-> (account ctx
address)
(.isActor)))
(defn address
"Returns the executing address of the given `ctx`."
^Address
[^Context ctx]
(.getAddress ctx))
(defn env
"Returns the environment of the executing account attached to `ctx`."
(^AHashMap [^Context ctx]
(.getEnvironment ctx))
(^AHashMap [ctx address]
(.getEnvironment (account ctx
address))))
(defn exception
"Returns the exception attached to the CVM (or nil).
The CVM enters in exceptional state in case of error or particular patterns such as
halting or doing a rollback.
A nil result means [[result]] can be safely used on this context.
An exception code can be provided as a filter, meaning that even if an exception occured, this
functions will return nil unless that exception has the given `code`.
Also see [[convex.cell/code-std*]] for easily retrieving an official error code. Note that in practice, unlike the CVM
itself or any of the core function, a user Convex function can return anything as a code."
(^AExceptional [^Context ctx]
(when (.isExceptional ctx)
(.getExceptional ctx)))
(^AExceptional [^ACell code ^Context ctx]
(when (.isExceptional ctx)
(let [e (.getExceptional ctx)]
(when (= (.getCode e)
code)
e)))))
(defn exception?
"Returns true if the given `ctx` is in an exceptional state.
See [[exception]]."
([^Context ctx]
(.isExceptional ctx))
([^ACell code ^Context ctx]
(if (.isExceptional ctx)
(= code
(.getCode (.getExceptional ctx)))
false)))
(defn exception-code
"Returns the code associated with the given [[exception]].
Often a CVX keyword but could be any CVX value."
^ACell
[^AExceptional exception]
(.getCode exception))
(defn exception-message
"Returns the message associated with the given [[exception]].
Often a CVX string but could be any CVX value."
^ACell
[^AExceptional exception]
(.getMessage exception))
(defn exception-trace
"Returns the trace associated with the given [[exception]] (CVX list of strings)."
^ACell
[^ErrorValue exception]
(.getTrace exception))
(defn juice
"Returns the amount of juice consumed so far in the given context.
Also see [[juice-set]]."
[^Context ctx]
(.getJuiceUsed ctx))
(defn juice-available
"Returns the amount of juice available for execution according to [[juice]] and [[juice-limit]]."
[^Context ctx]
(.getJuiceAvailable ctx))
(defn juice-limit
"Returns the maximum amount of juice that can be consumed."
[^Context ctx]
(.getJuiceLimit ctx))
(defn key
"Returns the key of the given `address`.
Or the address associated with `ctx`."
(^AccountKey [ctx]
(.getAccountKey (account ctx)))
(^AccountKey [ctx address]
(.getAccountKey (account ctx
address))))
(defn log
"Returns the log of `ctx`.
A vector cell of size 2 vectors containing a logging address and a logged value."
^ABlobMap
[^Context ctx]
(.getLog ctx))
(defn look-up
"Returns the cell associated with the given `sym`.
From the environment of the given `address` (or the currently used one)."
(^ACell [ctx sym]
(-> ctx
(env)
($.std/get sym)))
(^ACell [ctx address sym]
(-> ctx
(env address)
($.std/get sym))))
(defn result
"Extracts the result (eg. after expansion, compilation, execution, ...) wrapped in a `ctx`.
Throws if the `ctx` is in an exceptional state. See [[exception]]."
[^Context ctx]
(.getResult ctx))
(defn state
"Returns the whole CVM state associated with `ctx`.
It is a special type of cell behaving like a map cell. It notably holds all accounts and can be explored
using [[convex.std]] map functions.
Also see [[state-set]]."
^State
[^Context ctx]
(.getState ctx))
(defn time
"Returns the current timestamp assigned to the state in the given `ctx`.
A timetamp is a Unix epoch in milliseconds (long cell);
Also see [[time-set]]."
^CVMLong
[^Context ctx]
(-> ctx
(state)
(.getTimestamp)))
;;;;;;;;;; Modifying context properties
(defn account-create
"Creates an new account, with a `key` (user) or without (actor).
See [[convex.cell/key]].
Address is attached as a result in the returned context."
(^Context [^Context ctx]
(.createAccount ctx
nil))
(^Context [^Context ctx key]
(.createAccount ctx
key)))
(defn def
"Like calling `(def sym value)` in Convex Lisp, either in the current address of the given one.
Argument is a map of `symbol cell` -> `cell`."
(^Context [ctx sym->value]
(convex.cvm/def ctx
(address ctx)
sym->value))
(^Context [^Context ctx addr sym->value]
(let [s (state ctx)
a (.getAccount s
addr)]
(if a
(state-set ctx
(.putAccount s
addr
(.withEnvironment a
(reduce (fn [env [^ACell sym ^ACell value]]
($.std/assoc env
sym
value))
(.getEnvironment a)
sym->value))))
ctx))))
(defn deploy
"Deploys the given `code` as an actor.
Returns a context that is either [[exception]]al or has the address of the successfully created actor
attached as a [[result]]."
^Context
[^Context ctx code]
(.deployActor ctx
(into-array ACell
[code])))
(defn exception-clear
"Removes the currently attached exception from the given `ctx`."
^Context
[^Context ctx]
(.withException ctx
nil))
(defn exception-set
"Returns a `ctx` set in an exceptional state.
See [[exception]]."
(^Context [^Context ctx ^AExceptional exception]
(.withException ctx
exception))
(^Context [^Context ctx ^ACell code ^ACell message]
(.withError ctx
(ErrorValue/createRaw code
message))))
(defn juice-preserve
"Executes `(f ctx)`, `f` being a function `ctx` -> `ctx`.
The returned `ctx` will have the same amount of juice as the original."
^Context
[ctx f]
(let [juice- (juice ctx)]
(.withJuice ^Context (f ctx)
juice-)))
(defn juice-refill
"Resets the value of [[juice]] to `0`.
Also see [[juice-set]].
Returns an update context."
^Context
[^Context ctx]
(juice-set ctx
0))
(defn juice-set
"Sets the value of [[juice]] to the requested `amount`.
Also see [[juice]], [[juice-refill]].
Returns an update context."
^Context
[^Context ctx amount]
(.withJuice ctx
amount))
(defn juice-limit-set
"Sets the value of [[juice-limit]] to the requested `amount`.
Returns an update context."
^Context
[^Context ctx amount]
(.withJuiceLimit ctx
amount))
(defn key-set
"Sets `key` on the address curently associated with `ctx`."
^Context
[^Context ctx ^AccountKey key]
(.setAccountKey ctx
key))
(defn result-set
"Attaches the given `result` to `ctx`, as if it was the result of a transaction."
^Context
[^Context ctx ^ACell result]
(.withResult ctx
result))
(defn state-set
"Replaces the CVM state in the `ctx` with the given one.
Attention, will fail if the [[address]] does not exist in the new `state`.
See [[state]]."
^Context
[^Context ctx ^State state]
(.withState ctx
state))
(defn time-advance
"Advances the timestamp in the state of `ctx` by `millis` milliseconds.
Scheduled transactions will be executed if necessary.
Does not do anything if `millis` is < 0.
See [[time]]."
^Context
[^Context ctx millis]
(state-set ctx
(-> ctx
(state)
(.applyBlock (Block/create (long (+ (.longValue (time ctx))
millis))
($.cell/vector [])))
(.getState))))
(defn undef
"Like calling `(undef sym)` in Convex Lisp.
Either in the current account or the given one, repeatedly on any symbol cell in `sym+`."
(^Context [ctx sym+]
(undef ctx
(address ctx)
sym+))
(^Context [^Context ctx addr sym+]
(let [s (state ctx)
a (.getAccount s
addr)]
(if a
(state-set ctx
(.putAccount s
addr
(.withEnvironment a
(reduce (fn [^AHashMap env ^ACell sym]
(.dissoc env
sym))
(.getEnvironment a)
sym+))))
ctx))))
;;;;;;;;;; Phase 1 & 2 - Expanding Convex objects and compiling into operations
(defn expand
"Expands `cell` into a `canonical cell` by applying macros.
Fetched using [[result]] if not given.
Returns a new `ctx` with a [[result]] ready for [[compile]] or an [[exception]] in case
of failure."
(^Context [ctx]
(expand ctx
(result ctx)))
(^Context [^Context ctx cell]
(.expand ctx
cell)))
(defn compile
"Compiles the `canonical-cell` into executable code.
Fetched using [[result]] if not given.
Returns a new `ctx` with a [[result]] ready for [[exec]] or an [[exception]] in case of
failure."
(^Context [ctx]
(compile ctx
(result ctx)))
(^Context [^Context ctx canonical-cell]
(.compile ctx
canonical-cell)))
(defn expand-compile
"Expands and compiles in one go.
More efficient than chaining [[expand]] and [[compile]] yourself."
(^Context [ctx]
(expand-compile ctx
(result ctx)))
(^Context [^Context ctx cell]
(.expandCompile ctx
cell)))
;;;;;;;;;; Phase 3 - Executing compiled code
(defn exec
"Executes compiled code.
Usually run after [[compile]].
Returns a new `ctx` with a [[result]] or an [[exception]] in case of failure."
(^Context [ctx]
(exec ctx
(result ctx)))
(^Context [^Context ctx ^AOp op]
(.run ctx
op)))
;;;
(defn eval
"Evaluates the given `cell` after forking the `ctx`.
Goes efficiently through [[expand]], [[compile]], and [[exec]].
Works with any kind of `cell` and is sufficient when there is no need for fine-grained control.
An important difference with the aforementioned cycle is that the cell passes through `*lang*`, a function
possibly set by the user for intercepting a cell (eg. modifying the cell and evaluating in an alternative way).
Returns the forked `ctx` with a [[result]] or an [[exception]] in case of failure."
(^Context [ctx]
(eval ctx
(result ctx)))
(^Context [^Context ctx ^ACell cell]
(.run ctx
cell)))
;;;;;;;;;; Functions
(defmacro arg+*
"Prepares arguments for invokation.
See [[invoke]]."
[& arg+]
(let [sym-arr (gensym)]
`(let [~sym-arr ^"[Lconvex.core.data.ACell;" (make-array ACell
~(count arg+))]
~@(map (fn [i arg]
`(aset ~sym-arr
~i
~arg))
(range)
arg+)
~sym-arr)))
(defn invoke
"Invokes the given CVM `f`unction using the given `ctx`.
`arg+` is a Java array of cells. See [[arg+*]] for easily and efficiently creating one.
Returns a new `ctx` with a [[result]] or an [[exception]] in case of failure."
^Context
[^Context ctx ^AFn f arg+]
(let [ctx-2 (.invoke ctx
f
arg+)
ex (exception ctx-2)]
(if ex
(if (instance? ErrorValue
ex)
ctx-2
(exception-clear ctx-2))
ctx-2)))
;;;;;;;;;; Transactions
(defn transact
"Executes the given transaction.
This is exactly what a peer does when executing a transation from a block, after
validating its signature.
Similar to [[eval]] but:
- Temporarily switches to the account of the transaction
- Executes the code in that account
- Takes care of all the juice and memory accounting for that account
For creating transactions, see:
- [[convex.cell/call]]
- [[convex.cell/invoke]]
- [[convex.cell/transfer]]
Returns a new `ctx` with the [[result]] or [[exception]] attached."
[^Context ctx ^ATransaction trx]
(let [ctx-2 (-> ctx
(state)
(.applyTransaction trx))
ctx-3 (state-set ctx
(state ctx-2))]
(if (exception? ctx-2)
(exception-set ctx-3
(exception ctx-2))
(result-set ctx-3
(result ctx-2)))))