This repository was archived by the owner on Jan 9, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 116
Expand file tree
/
Copy pathNative.hs
More file actions
1452 lines (1296 loc) · 55.8 KB
/
Native.hs
File metadata and controls
1452 lines (1296 loc) · 55.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE MultiWayIf #-}
-- |
-- Module : Pact.Native
-- Copyright : (C) 2016 Stuart Popejoy
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Stuart Popejoy <stuart@kadena.io>
--
-- Pact builtins/standard library.
--
module Pact.Native
( natives
, nativeDefs
, moduleToMap
, distinctDef
, enforceDef
, enforceOneDef
, enumerateDef
, pactVersionDef
, formatDef
, strToIntDef
, strToListDef
, concatDef
, intToStrDef
, hashDef
, ifDef
, readDecimalDef
, readIntegerDef
, readStringDef
, baseStrToInt
, mapDef
, zipDef
, foldDef
, makeListDef
, reverseDef
, filterDef
, sortDef
, whereDef
, composeDef
, lengthDef
, takeDef
, dropDef
, atDef
, chainDataSchema
, cdChainId, cdBlockHeight, cdBlockTime, cdSender, cdGasLimit, cdGasPrice
, describeNamespaceSchema
, dnUserGuard, dnAdminGuard, dnNamespaceName
, cdPrevBlockHash
) where
import Control.Arrow hiding (app)
import Control.Exception.Safe
import Control.Lens hiding (parts,Fold,contains)
import Control.Monad
import Control.Monad.IO.Class
import qualified Data.Attoparsec.Text as AP
import Data.Bool (bool)
import qualified Data.ByteString as BS
import qualified Data.Char as Char
import Data.Bits
import Data.Default
import Data.Functor(($>))
import Data.Foldable
import qualified Data.HashMap.Strict as HM
import qualified Data.Map.Strict as M
import qualified Data.List as L (nubBy)
import qualified Data.Set as S
import Data.Text (Text, pack, unpack)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Pact.Time
import qualified Data.Vector as V
import qualified Data.Vector.Algorithms.Intro as V
import Numeric
import Pact.Eval
import Pact.Native.Capabilities
import Pact.Native.Db
import Pact.Native.Decrypt
import Pact.Native.Guards
import Pact.Native.Internal
import Pact.Native.Keysets
import Pact.Native.Ops
import Pact.Native.SPV
import Pact.Native.Time
import Pact.Native.Pairing(zkDefs)
import Pact.Parse
import Pact.Runtime.Capabilities
import Pact.Runtime.Utils(lookupFreeVar)
import Pact.Types.Hash
import Pact.Types.Names
import Pact.Types.PactValue
import Pact.Types.Pretty hiding (list)
import Pact.Types.Purity
import Pact.Types.Runtime
import Pact.Types.Version
import Pact.Types.Namespace
import qualified Pact.JSON.Encode as J
-- | All production native modules.
natives :: [NativeModule]
natives =
[ langDefs
, dbDefs
, timeDefs
, opDefs
, keyDefs
, capDefs
, spvDefs
, decryptDefs
, guardDefs
, zkDefs
]
-- | Production native modules as a dispatch map.
nativeDefs :: HM.HashMap Text Ref
nativeDefs = mconcat $ map moduleToMap natives
moduleToMap :: NativeModule -> HM.HashMap Text Ref
moduleToMap = HM.fromList . map (asString *** Direct) . snd
lengthDef :: NativeDef
lengthDef = defRNative "length" length' (funType tTyInteger [("x",listA)])
["(length [1 2 3])", "(length \"abcdefgh\")", "(length { \"a\": 1, \"b\": 2 })"]
"Compute length of X, which can be a list, a string, or an object."
listA :: Type n
listA = mkTyVar "a" [TyList (mkTyVar "l" []),TyPrim TyString,TySchema TyObject (mkSchemaVar "o") def]
enforceDef :: NativeDef
enforceDef = defNative "enforce" enforce
(funType tTyBool [("test",tTyBool),("msg",tTyString)])
[ExecErrExample "(enforce (!= (+ 2 2) 4) \"Chaos reigns\")"]
"Fail transaction with MSG if pure expression TEST is false. Otherwise, returns true."
where
enforce :: NativeFun e
enforce i as = runSysOnly $ gasUnreduced i as $
ifExecutionFlagSet FlagDisablePact45
(mapM reduce as >>= enforce' i)
(enforceLazy i as)
enforce' :: RNativeFun e
enforce' i [TLiteral (LBool b') _,TLitString msg]
| b' = return $ TLiteral (LBool True) def
| otherwise = failTx (_faInfo i) $ pretty msg
enforce' i as = argsError i as
enforceLazy i [cond, msg] =
reduce cond >>= \case
TLiteral (LBool b') _ ->
if b' then
return (TLiteral (LBool True) def)
else reduce msg >>= \case
TLitString msg' -> failTx (_faInfo i) $ pretty msg'
e -> isOffChainForkedError FlagDisablePact47 >>= \case
OffChainError -> evalError' i $ "Invalid message argument, expected string " <> pretty e
OnChainError -> evalError' i $ "Invalid message argument, expected string, received argument of type: " <> pretty (typeof' e)
cond' -> reduce msg >>= argsError i . reverse . (:[cond'])
enforceLazy i as = mapM reduce as >>= argsError i
enforceOneDef :: NativeDef
enforceOneDef =
defNative "enforce-one" enforceOne (funType tTyBool [("msg",tTyString),("tests",TyList tTyBool)])
["(enforce-one \"Should succeed on second test\" [(enforce false \"Skip me\") (enforce (= (+ 2 2) 4) \"Chaos reigns\")])"]
"Run TESTS in order (in pure context, plus keyset enforces). If all fail, fail transaction. Short-circuits on first success."
where
enforceBool i e = reduce e >>= \case
tl@(TLiteral (LBool cond) _) -> if cond then pure (Just tl) else pure Nothing
_ -> evalError' i "Failure: expected boolean result in enforce-one"
catchTxFailure :: PactError -> Eval e (Maybe (Term Name))
catchTxFailure e = case peType e of
TxFailure -> pure Nothing
_ -> throwM e
enforceOne :: NativeFun e
enforceOne i as@[msg,TList conds _ _] = runReadOnly i $
gasUnreduced i as $ do
msg' <- reduce msg >>= \case
TLitString s -> return s
_ -> argsError' i as
let tryCond r@Just {} _ = return r
tryCond Nothing cond = isExecutionFlagSet FlagDisablePact44 >>= \case
True -> do
g <- getGas
catch (Just <$> reduce cond)
-- TODO: instead of catching all here, make pure violations
-- independently catchable
(\(_ :: SomeException) -> putGas g *> return Nothing)
False -> catch (enforceBool i cond) catchTxFailure
r <- foldM tryCond Nothing conds
case r of
Nothing -> failTx (_faInfo i) $ pretty msg'
Just b' -> return b'
enforceOne i as = argsError' i as
tryDef :: NativeDef
tryDef =
defNative "try" try' (funType a [("default", a), ("action", a)])
["(try 3 (enforce (= 1 2) \"this will definitely fail\"))"
,LitExample "(expect \"impure expression fails and returns default\" \"default\" \
\(try \"default\" (with-read accounts id {'ccy := ccy}) ccy))"
]
"Attempt a pure ACTION, returning DEFAULT in the case of failure. Pure expressions \
\are expressions which do not do i/o or work with non-deterministic state in contrast \
\to impure expressions such as reading and writing to a table."
where
try' :: NativeFun e
try' i as@[da, action] = gasUnreduced i as $ isExecutionFlagSet FlagDisablePact44 >>= \case
True -> do
ra <- reduce da
g1 <- getGas
-- TODO: instead of catching all here, make pure violations
-- independently catchable
catch (runReadOnly i $ reduce action) $ \(_ :: SomeException) -> do
putGas g1
return ra
False -> do
catch (runReadOnly i $ reduce action) $ \(e :: PactError) -> case peType e of
TxFailure -> reduce da
_ -> throwM e
try' i as = argsError' i as
pactVersionDef :: NativeDef
pactVersionDef = setTopLevelOnly $ defRNative "pact-version"
pactVersion'
(funType tTyString [])
["(pact-version)"]
"Obtain current pact build version."
where
-- note the 4.2.1 hardcode is
-- for compat across versions since it was previously set
-- by the cabal macro.
-- After pact 4.3.1, this is a local-only call and thus
-- we can use the cabal-generated version.
pactVersion' :: RNativeFun e
pactVersion' i _ = do
cond <- isExecutionFlagSet FlagDisablePact431
if cond then pure (toTerm compatVersion)
else checkNonLocalAllowed i *> pure (toTerm pactVersion)
where
compatVersion :: Text
compatVersion = "4.2.1"
formatDef :: NativeDef
formatDef =
defRNative "format" format
(funType tTyString [("template",tTyString),("vars",TyList TyAny)])
["(format \"My {} has {}\" [\"dog\" \"fleas\"])"]
"Interpolate VARS into TEMPLATE using {}."
strToListDef :: NativeDef
strToListDef = defGasRNative "str-to-list" strToList
(funType (TyList tTyString) [("str", tTyString)] )
[ "(str-to-list \"hello\")"
, "(concat (map (+ \" \") (str-to-list \"abcde\")))"
]
"Takes STR and returns a list of single character strings"
concatDef :: NativeDef
concatDef = defGasRNative "concat" concat'
(funType tTyString [("str-list", TyList tTyString)] )
[ "(concat [\"k\" \"d\" \"a\"])"
, "(concat (map (+ \" \") (str-to-list \"abcde\")))"
]
"Takes STR-LIST and concats each of the strings in the list, returning the resulting string"
strToIntDef :: NativeDef
strToIntDef = defRNative "str-to-int" strToInt
(funType tTyInteger [("str-val", tTyString)] <>
funType tTyInteger [("base", tTyInteger), ("str-val", tTyString)])
["(str-to-int 16 \"abcdef123456\")"
,"(str-to-int \"123456\")"
,"(str-to-int 64 \"q80\")"
]
"Compute the integer value of STR-VAL in base 10, or in BASE if specified. \
\STR-VAL can be up to 512 chars in length. \
\BASE must be between 2 and 16, or 64 to perform unpadded base64url conversion. \
\Each digit must be in the correct range for the base."
intToStrDef :: NativeDef
intToStrDef = defRNative "int-to-str" intToStr
(funType tTyString [("base",tTyInteger),("val",tTyInteger)])
["(int-to-str 16 65535)","(int-to-str 64 43981)"]
"Represent integer VAL as a string in BASE. BASE can be 2-16, or 64 for unpadded base64URL. \
\Only positive values are allowed for base64URL conversion."
where
intToStr _ [b'@(TLitInteger base),v'@(TLitInteger v)]
| base >= 2 && base <= 16 =
return $ toTerm $ T.pack $
showIntAtBase base Char.intToDigit v ""
| base == 64 && v >= 0 = doBase64 v
| base == 64 = evalError' v' "Only positive values allowed for base64URL conversion."
| otherwise = evalError' b' "Invalid base, must be 2-16 or 64"
intToStr i as = argsError i as
doBase64 v = return $ toTerm $ toB64UrlUnpaddedText $ integerToBS v
hashDef :: NativeDef
hashDef = defRNative "hash" hash' (funType tTyString [("value",a)])
["(hash \"hello\")", "(hash { 'foo: 1 })"]
"Compute BLAKE2b 256-bit hash of VALUE represented in unpadded base64-url. \
\Strings are converted directly while other values are \
\converted using their JSON representation. Non-value-level arguments are not allowed."
where
hash' :: RNativeFun e
hash' i as = case as of
[TLitString s] -> go $ T.encodeUtf8 s
[a'] -> enforcePactValue a' >>= go . J.encodeStrict
_ -> argsError i as
where go = return . tStr . asString . pactHash
ifDef :: NativeDef
ifDef = defNative "if" if' (funType a [("cond",tTyBool),("then",a),("else",a)])
["(if (= (+ 2 2) 4) \"Sanity prevails\" \"Chaos reigns\")"]
"Test COND. If true, evaluate THEN. Otherwise, evaluate ELSE."
where
if' :: NativeFun e
if' i as@[cond,then',else'] = gasUnreduced i as $ reduce cond >>= \case
TLiteral (LBool c') _ -> reduce (if c' then then' else else')
t -> isOffChainForkedError FlagDisablePact47 >>= \case
OffChainError -> evalError' i $ "if: conditional not boolean: " <> pretty t
OnChainError -> evalError' i $ "if: conditional not boolean, received value of type: " <> pretty (typeof' t)
if' i as = argsError' i as
readDecimalDef :: NativeDef
readDecimalDef = defRNative "read-decimal" readDecimal
(funType tTyDecimal [("key",tTyString)])
[LitExample "(defun exec ()\n (transfer (read-msg \"from\") (read-msg \"to\") (read-decimal \"amount\")))"]
"Parse KEY string or number value from top level of message data body as decimal."
where
readDecimal :: RNativeFun e
readDecimal i [TLitString key] = do
(ParsedDecimal a') <- parseMsgKey i "read-decimal" key
return $ toTerm a'
readDecimal i as = argsError i as
readIntegerDef :: NativeDef
readIntegerDef = defRNative "read-integer" readInteger
(funType tTyInteger [("key",tTyString)])
[LitExample "(read-integer \"age\")"]
"Parse KEY string or number value from top level of message data body as integer."
where
readInteger :: RNativeFun e
readInteger i [TLitString key] = do
(ParsedInteger a') <- parseMsgKey i "read-integer" key
return $ toTerm a'
readInteger i as = argsError i as
readStringDef :: NativeDef
readStringDef = defRNative "read-string" readString
(funType tTyString [("key",tTyString)])
[LitExample "(read-string \"sender\")"]
"Parse KEY string or number value from top level of message data body as string."
where
readString :: RNativeFun e
readString i [TLitString key] = do
txt <- parseMsgKey i "read-string" key
return $ tStr txt
readString i as = argsError i as
toGuardPactValue :: Guard (Term Name) -> Either Text (Guard PactValue)
toGuardPactValue g = case g of
(GUser (UserGuard n ts)) -> do
pvs <- map elideModRefInfo <$> traverse toPactValue ts
return (GUser (UserGuard n pvs))
(GCapability (CapabilityGuard n ts pid)) -> do
pvs <- map elideModRefInfo <$> traverse toPactValue ts
return (GCapability (CapabilityGuard n pvs pid))
(GKeySet k) -> Right (GKeySet k)
(GKeySetRef k) -> Right (GKeySetRef k)
(GModule m) -> Right (GModule m)
(GPact p) -> Right (GPact p)
fromGuardPactValue :: Guard PactValue -> Guard (Term Name)
fromGuardPactValue g = case g of
(GUser (UserGuard n ts)) -> GUser (UserGuard n (map fromPactValue ts))
(GCapability (CapabilityGuard n ts pid)) ->
GCapability (CapabilityGuard n (map fromPactValue ts) pid)
(GKeySet k) -> GKeySet k
(GKeySetRef k) -> GKeySetRef k
(GModule m) -> GModule m
(GPact p) -> GPact p
toNamespacePactValue :: Info -> Namespace (Term Name) -> Eval e (Namespace PactValue)
toNamespacePactValue info (Namespace name userg adming) = do
usergPv <- throwEitherText EvalError info
"Failed converting namespace user guard to pact value"
(toGuardPactValue userg)
admingPv <- throwEitherText EvalError info
"Failed converting namespace admin guard to pact value"
(toGuardPactValue adming)
return (Namespace name usergPv admingPv)
fromNamespacePactValue :: Namespace PactValue -> Namespace (Term Name)
fromNamespacePactValue (Namespace n userg adming) =
Namespace n (fromGuardPactValue userg) (fromGuardPactValue adming)
dnUserGuard :: FieldKey
dnUserGuard = "user-guard"
dnAdminGuard :: FieldKey
dnAdminGuard = "admin-guard"
dnNamespaceName :: FieldKey
dnNamespaceName = "namespace-name"
describeNamespaceSchema :: NativeDef
describeNamespaceSchema = defSchema "described-namespace"
"Schema type for data returned from 'describe-namespace'."
[ (dnUserGuard, tTyGuard Nothing)
, (dnAdminGuard, tTyGuard Nothing)
, (dnNamespaceName, tTyString)
]
describeNamespaceDef :: NativeDef
describeNamespaceDef = setTopLevelOnly $ defGasRNative
"describe-namespace" describeNamespace
(funType (tTyObject dnTy) [("ns", tTyString)])
[LitExample "(describe-namespace 'my-namespace)"]
"Describe the namespace NS, returning a row object containing \
\the user and admin guards of the namespace, as well as its name."
where
dnTy = TyUser (snd describeNamespaceSchema)
describeNamespace :: GasRNativeFun e
describeNamespace i as = case as of
[TLitString nsn] -> do
readRow (getInfo i) Namespaces (NamespaceName nsn) >>= \case
Just ns@(Namespace nsn' user admin) -> do
let guardTermOf g = TGuard (fromPactValue <$> g) def
computeGas' i (GPostRead (ReadNamespace ns)) $
pure $ toTObject dnTy def
[ (dnUserGuard, guardTermOf user)
, (dnAdminGuard, guardTermOf admin)
, (dnNamespaceName, toTerm $ renderCompactText nsn')
]
Nothing -> evalError' i $ "Namespace not defined: " <> pretty nsn
_ -> argsError i as
defineNamespaceDef :: NativeDef
defineNamespaceDef = setTopLevelOnly $ defGasRNative "define-namespace" defineNamespace
(funType tTyString [("namespace", tTyString), ("user-guard", tTyGuard Nothing), ("admin-guard", tTyGuard Nothing)])
[LitExample "(define-namespace 'my-namespace (read-keyset 'user-ks) (read-keyset 'admin-ks))"]
"Create a namespace called NAMESPACE where ownership and use of the namespace is controlled by GUARD. \
\If NAMESPACE is already defined, then the guard previously defined in NAMESPACE will be enforced, \
\and GUARD will be rotated in its place."
where
defineNamespace :: GasRNativeFun e
defineNamespace i as = case as of
[TLitString nsn, TGuard userg _, TGuard adming _] -> case parseName (_faInfo i) nsn of
Left _ -> evalError' i $ "invalid namespace name format: " <> pretty nsn
Right _ -> go i nsn userg adming
_ -> argsError i as
go fi nsn ug ag = do
let name = NamespaceName nsn
info = _faInfo fi
newNs = Namespace name ug ag
newNsPactValue <- toNamespacePactValue info newNs
mOldNs <- readRow info Namespaces name
szVer <- getSizeOfVersion
case (fromNamespacePactValue <$> mOldNs) of
Just ns@(Namespace _ _ oldg) -> do
-- if namespace is defined, enforce old guard
nsPactValue <- toNamespacePactValue info ns
computeGas (Right fi) (GPostRead (ReadNamespace nsPactValue))
withMagicNsCap fi name $ enforceGuard fi oldg
computeGas' fi (GPreWrite (WriteNamespace newNsPactValue) szVer) $
writeNamespace info name newNsPactValue
Nothing -> do
withMagicNsCap fi name $ enforcePolicy info name newNs
computeGas' fi (GPreWrite (WriteNamespace newNsPactValue) szVer) $
writeNamespace info name newNsPactValue
withMagicNsCap i (NamespaceName name) =
withMagicCapability i "DEFINE_NAMESPACE" [PLiteral (LString name)]
enforcePolicy info nn ns = do
policy <- view eeNamespacePolicy
allowNs <- case policy of
SimpleNamespacePolicy f -> return $ f (Just ns)
SmartNamespacePolicy _ fun -> applyNsPolicyFun fun fun nn ns
unless allowNs $ evalError info "Namespace definition not permitted"
writeNamespace info nn ns =
success ("Namespace defined: " <> asString nn) $ do
writeRow info Write Namespaces nn ns
applyNsPolicyFun :: HasInfo i => i -> QualifiedName -> NamespaceName
-> (Namespace (Term Name)) -> Eval e Bool
applyNsPolicyFun fi fun nn ns = do
let i = getInfo fi
refm <- resolveRef i (QName fun)
def' <- case refm of
(Just (Ref d@TDef {})) -> return d
Just t -> evalError i $ "invalid ns policy fun: " <> pretty t
Nothing -> evalError i $ "ns policy fun not found: " <> pretty fun
asBool =<< apply (App def' [] i) mkArgs
where
asBool (TLiteral (LBool allow) _) = return allow
asBool t = isOffChainForkedError FlagDisablePact47 >>= \case
OffChainError -> evalError' fi $ "Unexpected return value from namespace policy: " <> pretty t
OnChainError -> evalError' fi $ "Unexpected return value from namespace policy, received value of type: " <> pretty (typeof' t)
mkArgs = [toTerm (asString nn),TGuard (_nsAdmin ns) def]
namespaceDef :: NativeDef
namespaceDef = setTopLevelOnly $ defGasRNative "namespace" namespace
(funType tTyString [("namespace", tTyString)])
[LitExample "(namespace 'my-namespace)"]
"Set the current namespace to NAMESPACE. All expressions that occur in a current \
\transaction will be contained in NAMESPACE, and once committed, may be accessed \
\via their fully qualified name, which will include the namespace. Subsequent \
\namespace calls in the same tx will set a new namespace for all declarations \
\until either the next namespace declaration, or the end of the tx."
where
namespace :: GasRNativeFun e
namespace i as = case as of
[TLitString nsn] ->
ifExecutionFlagSet FlagDisablePact47
(go i nsn)
(if T.null nsn then
goEmpty i
else go i nsn)
_ -> argsError i as
goEmpty fa = computeGas' fa (GUnreduced [])
$ success "Namespace reset to root"
$ evalRefs . rsNamespace .= Nothing
go fa ns = do
let name = NamespaceName ns
info = _faInfo fa
mNs <- readRow info Namespaces name
case fromNamespacePactValue <$> mNs of
Just n@(Namespace ns' g _) -> do
nsPactValue <- toNamespacePactValue info n
computeGas' fa (GPostRead (ReadNamespace nsPactValue)) $ do
-- Old behavior enforces ns at declaration.
-- Old behavior does not offer magic cap.
-- New behavior enforces at ns-related action:
-- 1. Module install (NOT at module upgrade)
-- 2. Interface install (Interfaces non-upgradeable)
-- 3. Namespaced keyset definition (once #351 is in)
whenExecutionFlagSet FlagDisablePact44 $ enforceGuard fa g
success ("Namespace set to " <> (asString ns')) $
evalRefs . rsNamespace .= (Just n)
Nothing -> evalError info $
"namespace: '" <> pretty name <> "' not defined"
cdChainId :: FieldKey
cdChainId = "chain-id"
cdBlockHeight :: FieldKey
cdBlockHeight = "block-height"
cdBlockTime :: FieldKey
cdBlockTime = "block-time"
cdPrevBlockHash :: FieldKey
cdPrevBlockHash = "prev-block-hash"
cdSender :: FieldKey
cdSender = "sender"
cdGasLimit :: FieldKey
cdGasLimit = "gas-limit"
cdGasPrice :: FieldKey
cdGasPrice = "gas-price"
chainDataSchema :: NativeDef
chainDataSchema = defSchema "public-chain-data"
"Schema type for data returned from 'chain-data'."
[ (cdChainId, tTyString)
, (cdBlockHeight, tTyInteger)
, (cdBlockTime, tTyTime)
, (cdPrevBlockHash, tTyString)
, (cdSender, tTyString)
, (cdGasLimit, tTyInteger)
, (cdGasPrice, tTyDecimal)
]
chainDataDef :: NativeDef
chainDataDef = defRNative "chain-data" chainData
(funType (tTyObject pcTy) [])
["(chain-data)"]
"Get transaction public metadata. Returns an object with 'chain-id', 'block-height', \
\'block-time', 'prev-block-hash', 'sender', 'gas-limit', 'gas-price', and 'gas-fee' fields."
where
pcTy = TyUser (snd chainDataSchema)
chainData :: RNativeFun e
chainData _ [] = do
PublicData{..} <- view eePublicData
let PublicMeta{..} = _pdPublicMeta
toTime = toTerm . fromPosixTimestampMicros
pure $ toTObject TyAny def
[ (cdChainId, toTerm _pmChainId)
, (cdBlockHeight, toTerm _pdBlockHeight)
, (cdBlockTime, toTime _pdBlockTime)
, (cdPrevBlockHash, toTerm _pdPrevBlockHash)
, (cdSender, toTerm _pmSender)
, (cdGasLimit, toTerm _pmGasLimit)
, (cdGasPrice, toTerm _pmGasPrice)
]
chainData i as = argsError i as
mapDef :: NativeDef
mapDef = defNative "map" map'
(funType (TyList a) [("app",lam b a),("list",TyList b)])
["(map (+ 1) [1 2 3])"]
"Apply APP to each element in LIST, returning a new list of results."
foldDef :: NativeDef
foldDef = defNative "fold" fold'
(funType a [("app",lam2 a b a),("init",a),("list",TyList b)])
["(fold (+) 0 [100 10 5])"]
"Iteratively reduce LIST by applying APP to last result and element, starting with INIT."
makeListDef :: NativeDef
makeListDef = defGasRNative "make-list" makeList (funType (TyList a) [("length",tTyInteger),("value",a)])
["(make-list 5 true)"]
"Create list by repeating VALUE LENGTH times."
enumerateDef :: NativeDef
enumerateDef = defGasRNative "enumerate" enumerate
(funType (TyList tTyInteger) [("from", tTyInteger), ("to", tTyInteger),("inc", tTyInteger)]
<> funType (TyList tTyInteger) [("from", tTyInteger), ("to", tTyInteger)])
["(enumerate 0 10 2)"
, "(enumerate 0 10)"
, "(enumerate 10 0)"]
$ T.intercalate " "
[ "Returns a sequence of numbers from FROM to TO (both inclusive) as a list."
, "INC is the increment between numbers in the sequence."
, "If INC is not given, it is assumed to be 1."
, "Additionally, if INC is not given and FROM is greater than TO assume a value for INC of -1."
, "If FROM equals TO, return the singleton list containing FROM, irrespective of INC's value."
, "If INC is equal to zero, this function will return the singleton list containing FROM."
, "If INC is such that FROM + INC > TO (when FROM < TO) or FROM + INC < TO (when FROM > TO) return the singleton list containing FROM."
, "Lastly, if INC is such that FROM + INC < TO (when FROM < TO) or FROM + INC > TO (when FROM > TO), then this function fails."
]
reverseDef :: NativeDef
reverseDef = defRNative "reverse" reverse' (funType (TyList a) [("list",TyList a)])
["(reverse [1 2 3])"] "Reverse LIST."
filterDef :: NativeDef
filterDef = defNative "filter" filter'
(funType (TyList a) [("app",lam a tTyBool),("list",TyList a)])
["(filter (compose (length) (< 2)) [\"my\" \"dog\" \"has\" \"fleas\"])"]
"Filter LIST by applying APP to each element. For each true result, the original value is kept."
distinctDef :: NativeDef
distinctDef = defGasRNative "distinct" distinct
(funType (TyList a) [("values", TyList a)])
["(distinct [3 3 1 1 2 2])"]
$ T.intercalate " "
[ "Returns from a homogeneous list of VALUES a list with duplicates removed."
, "The original order of the values is preserved."]
sortDef :: NativeDef
sortDef = defGasRNative "sort" sort'
(funType (TyList a) [("values",TyList a)] <>
funType (TyList (tTyObject (mkSchemaVar "o"))) [("fields",TyList tTyString),("values",TyList (tTyObject (mkSchemaVar "o")))])
["(sort [3 1 2])", "(sort ['age] [{'name: \"Lin\",'age: 30} {'name: \"Val\",'age: 25}])"]
"Sort a homogeneous list of primitive VALUES, or objects using supplied FIELDS list."
whereDef :: NativeDef
whereDef = defNative (specialForm Where) where'
(funType tTyBool [("field",tTyString),("app",lam a tTyBool),("value",tTyObject (mkSchemaVar "row"))])
["(filter (where 'age (> 20)) [{'name: \"Mary\",'age: 30} {'name: \"Juan\",'age: 15}])"]
"Utility for use in 'filter' and 'select' applying APP to FIELD in VALUE."
composeDef :: NativeDef
composeDef = defNative "compose" compose (funType c [("x",lam a b),("y", lam b c),("value",a)])
["(filter (compose (length) (< 2)) [\"my\" \"dog\" \"has\" \"fleas\"])"]
"Compose X and Y, such that X operates on VALUE, and Y on the results of X."
takeDef :: NativeDef
takeDef = defRNative "take" take' takeDrop
[ "(take 2 \"abcd\")"
, "(take (- 3) [1 2 3 4 5])"
, "(take ['name] { 'name: \"Vlad\", 'active: false})"
]
"Take COUNT values from LIST (or string), or entries having keys in KEYS from OBJECT. If COUNT is negative, take from end. If COUNT exceeds the interval (-2^63,2^63), it is truncated to that range."
dropDef :: NativeDef
dropDef = defRNative "drop" drop' takeDrop
[ "(drop 2 \"vwxyz\")"
, "(drop (- 2) [1 2 3 4 5])"
, "(drop ['name] { 'name: \"Vlad\", 'active: false})"
]
"Drop COUNT values from LIST (or string), or entries having keys in KEYS from OBJECT. If COUNT is negative, drop from end. If COUNT exceeds the interval (-2^63,2^63), it is truncated to that range."
zipDef :: NativeDef
zipDef = defNative "zip" zip' zipTy
[ "(zip (+) [1 2 3 4] [4 5 6 7])"
, "(zip (-) [1 2 3 4] [4 5 6])"
, "(zip (+) [1 2 3] [4 5 6 7])"
]
"Combine two lists with some function f, into a new list, the length of which is the length of the shortest list."
atDef :: NativeDef
atDef = defRNative "at" at'
( funType a [("idx",tTyInteger),("list",TyList (mkTyVar "l" []))]
<> funType a [("idx",tTyString),("object",tTyObject (mkSchemaVar "o"))]
)
["(at 1 [1 2 3])", "(at \"bar\" { \"foo\": 1, \"bar\": 2 })"]
"Index LIST at IDX, or get value with key IDX from OBJECT."
asciiConst :: NativeDef
asciiConst = defConst "CHARSET_ASCII"
"Constant denoting the ASCII charset"
tTyInteger
(toTerm (0 :: Integer))
latin1Const :: NativeDef
latin1Const = defConst "CHARSET_LATIN1"
"Constant denoting the Latin-1 charset ISO-8859-1"
tTyInteger
(toTerm (1 :: Integer))
-- | Check that a given string conforms to a specified character set.
-- Supported character sets include latin (ISO 8859-1)
--
isCharsetDef :: NativeDef
isCharsetDef =
defRNative "is-charset" isCharset
(funType tTyBool [("charset", tTyInteger), ("input", tTyString)])
[ "(is-charset CHARSET_ASCII \"hello world\")"
, "(is-charset CHARSET_ASCII \"I am nÖt ascii\")"
, "(is-charset CHARSET_LATIN1 \"I am nÖt ascii, but I am latin1!\")"
]
"Check that a string INPUT conforms to the a supported character set CHARSET. \
\Character sets currently supported are: 'CHARSET_LATIN1' (ISO-8859-1), and \
\'CHARSET_ASCII' (ASCII). Support for sets up through ISO 8859-5 supplement will be \
\added in the future."
where
isCharset :: RNativeFun e
isCharset i as = case as of
[TLitInteger cs, TLitString t] -> case cs of
0 -> go Char.isAscii t
1 -> go Char.isLatin1 t
_ -> evalError' i $ "Unsupported character set: " <> pretty cs
_ -> argsError i as
go k = return . toTerm . T.all k
langDefs :: NativeModule
langDefs =
("General",[
ifDef
,mapDef
,foldDef
,defRNative "list" list
(funType (TyList TyAny) [("elems",TyAny)])
["(list 1 2 3)"]
"Create list from ELEMS. Deprecated in Pact 2.1.1 with literal list support."
,makeListDef
,enumerateDef
,reverseDef
,filterDef
,sortDef
,whereDef
,composeDef
,lengthDef
,takeDef
,dropDef
,zipDef
,defRNative "remove" remove (funType (tTyObject (mkSchemaVar "o")) [("key",tTyString),("object",tTyObject (mkSchemaVar "o"))])
["(remove \"bar\" { \"foo\": 1, \"bar\": 2 })"]
"Remove entry for KEY from OBJECT."
,atDef
,enforceDef
,enforceOneDef
,tryDef
,formatDef
,defRNative "pact-id" pactId (funType tTyString []) []
"Return ID if called during current pact execution, failing if not."
,readDecimalDef
,readIntegerDef
,readStringDef
,defRNative "read-msg" readMsg (funType a [] <> funType a [("key",tTyString)])
[LitExample "(defun exec ()\n (transfer (read-msg \"from\") (read-msg \"to\") (read-decimal \"amount\")))"]
"Read KEY from top level of message data body, or data body itself if not provided. \
\Coerces value to their corresponding pact type: String -> string, Number -> integer, Boolean -> bool, \
\List -> list, Object -> object."
,defRNative "tx-hash" txHash (funType tTyString []) ["(tx-hash)"]
"Obtain hash of current transaction as a string."
,defNative (specialForm Bind) bind
(funType a [("src",tTyObject row),("binding",TySchema TyBinding row def)])
["(bind { \"a\": 1, \"b\": 2 } { \"a\" := a-value } a-value)"]
"Special form evaluates SRC to an object which is bound to with BINDINGS over subsequent body statements."
,defRNative "typeof" typeof'' (funType tTyString [("x",a)])
["(typeof \"hello\")"] "Returns type of X as string."
,distinctDef
,setTopLevelOnly $ defRNative "list-modules" listModules
(funType (TyList tTyString) []) [] "List modules available for loading."
,defGasRNative (specialForm YieldSF) yield
(funType yieldv [("object",yieldv)] <>
funType yieldv [("object", yieldv), ("target-chain",tTyString)])
[ LitExample "(yield { \"amount\": 100.0 })"
, LitExample "(yield { \"amount\": 100.0 } \"some-chain-id\")"
]
"Yield OBJECT for use with 'resume' in following pact step. With optional argument TARGET-CHAIN, \
\target subsequent step to execute on targeted chain using automated SPV endorsement-based dispatch."
,defNative (specialForm Resume) resume
(funType a [("binding",TySchema TyBinding (mkSchemaVar "r") def)]) []
"Special form binds to a yielded object value from the prior step execution in a pact. \
\If yield step was executed on a foreign chain, enforce endorsement via SPV."
,pactVersionDef
,setTopLevelOnly $ defRNative "enforce-pact-version" enforceVersion
(funType tTyBool [("min-version",tTyString)] <>
funType tTyBool [("min-version",tTyString),("max-version",tTyString)])
["(enforce-pact-version \"2.3\")"]
"Enforce runtime pact version as greater than or equal MIN-VERSION, and less than or equal MAX-VERSION. \
\Version values are matched numerically from the left, such that '2', '2.2', and '2.2.3' would all allow '2.2.3'."
,defRNative "contains" contains
(funType tTyBool [("value",a),("list",TyList a)] <>
funType tTyBool [("key",a),("object",tTyObject (mkSchemaVar "o"))] <>
funType tTyBool [("value",tTyString),("string",tTyString)])
[ "(contains 2 [1 2 3])"
, "(contains 'name { 'name: \"Ted\", 'age: 72 })"
, "(contains \"foo\" \"foobar\")"
]
"Test that LIST or STRING contains VALUE, or that OBJECT has KEY entry."
,defNative "constantly" constantly
(funType a [("value",a),("ignore1",b)] <>
funType a [("value",a),("ignore1",b),("ignore2",c)] <>
funType a [("value",a),("ignore1",b),("ignore2",c),("ignore3",d)])
["(filter (constantly true) [1 2 3])"]
"Lazily ignore arguments IGNORE* and return VALUE."
,defRNative "identity" identity (funType a [("value",a)])
["(map (identity) [1 2 3])"] "Return provided value."
,defNative "continue" continueNested
(funType TyAny [("value", TyAny)]) [LitExample "(continue f)"]
"Continue a previously started nested defpact."
,strToIntDef
,strToListDef
,concatDef
,intToStrDef
,hashDef
,defineNamespaceDef
,describeNamespaceDef
,namespaceDef
,chainDataDef
,chainDataSchema
,isCharsetDef
,asciiConst
,latin1Const
,base64Encode
,base64decode
])
where
d = mkTyVar "d" []
row = mkSchemaVar "row"
yieldv = TySchema TyObject (mkSchemaVar "y") def
obj :: Type n
obj = tTyObject (mkSchemaVar "o")
listStringA :: Type n
listStringA = mkTyVar "a" [TyList (mkTyVar "l" []),TyPrim TyString]
takeDrop :: FunTypes n
takeDrop = funType listStringA [("count",tTyInteger),("list",listStringA)] <>
funType obj [("keys",TyList tTyString),("object",obj)]
zipTy :: FunTypes n
zipTy = funType (TyList c) [("f", TyFun $ funType' c [("x", a), ("y", b)]),("list1", TyList a), ("list2", TyList b)]
lam :: Type v -> Type v -> Type v
lam x y = TyFun $ funType' y [("x",x)]
lam2 :: Type v -> Type v -> Type v -> Type v
lam2 x y z = TyFun $ funType' z [("x",x),("y",y)]
a, b, c :: Type n
a = mkTyVar "a" []
b = mkTyVar "b" []
c = mkTyVar "c" []
map' :: NativeFun e
map' i as@[tLamToApp -> TApp app _,l] = gasUnreduced i as $ reduce l >>= \case
TList ls _ _ -> (\b' -> TList b' TyAny def) <$> forM ls (apply app . pure)
t ->
isOffChainForkedError FlagDisablePact47 >>= \case
OffChainError -> evalError' i $ "map: expecting list: " <> pretty (abbrev t)
OnChainError -> evalError' i $ "map: expecting list, received argument of type: " <> pretty (typeof' t)
map' i as = argsError' i as
list :: RNativeFun e
list i as = return $ TList (V.fromList as) TyAny (_faInfo i) -- TODO, could set type here
makeList :: GasRNativeFun e
makeList i [TLitInteger len,value] = case typeof value of
Right ty -> do
ts <- ifExecutionFlagSet' FlagDisablePact48 Pact43IntThreshold Pact48IntThreshold
ga <- ifExecutionFlagSet' FlagDisablePact45 (GMakeList len) (GMakeList2 len Nothing ts)
computeGas' i ga $ return $
toTListV ty def $ V.replicate (fromIntegral len) value
Left ty -> evalError' i $ "make-list: invalid value type: " <> pretty ty
makeList i as = argsError i as
enumerate :: GasRNativeFun e
enumerate i = \case
[TLitInteger from', TLitInteger to', TLitInteger inc] ->
createEnumerateList from' to' inc
[TLitInteger from', TLitInteger to'] ->
createEnumerateList from' to' $ bool 1 (-1) (from' > to')
as -> argsError i as
where
computeList
:: Integer
-- ^ the length of the list
-> Integer
-- ^ size of the largest element.
-> V.Vector Integer
-- ^ The generated vector
-> Eval e (Term Name)
computeList len sz v = do
ts <- ifExecutionFlagSet' FlagDisablePact48 Pact43IntThreshold Pact48IntThreshold
ga <- ifExecutionFlagSet' FlagDisablePact45 (GMakeList len) (GMakeList2 len (Just sz) ts)
computeGas' i ga $ pure $ toTListV tTyInteger def $ fmap toTerm v
step to' inc acc
| acc > to', inc > 0 = Nothing
| acc < to', inc < 0 = Nothing
| otherwise = Just (acc, acc + inc)
createEnumerateList from' to' inc
| from' == to' = computeList 1 from' (V.singleton from')
| inc == 0 = computeList 1 0 mempty
| from' < to', from' + inc < from' =
evalError' i "enumerate: increment diverges below from interval bounds."
| from' > to', from' + inc > from' =
evalError' i "enumerate: increment diverges above from interval bounds."
| otherwise = do
let g' = succ $ (abs (from' - to')) `div` (abs inc)
computeList g' (max (abs from') (abs to')) $ V.unfoldr (step to' inc) from'
reverse' :: RNativeFun e
reverse' i [l@TList{}] = do
unlessExecutionFlagSet FlagDisablePact48 $ computeGas (Right i) (GReverse listLen)
pure $ over tList V.reverse l
where
listLen = V.length $ view tList l
reverse' i args = argsError i args
format :: RNativeFun e
format i [TLitString s,TList es _ _] = do
let parts = T.splitOn "{}" s
plen = length parts
if | plen == 1 -> return $ tStr s
| plen - length es > 1 -> evalError' i "format: not enough arguments for template"
| otherwise -> do
args <- ifExecutionFlagSet FlagDisablePact48 formatLegacyArgs formatFullGassedArgs
return $ tStr $ T.concat $ alternate parts (take (plen - 1) args)
where
repVal (PLiteral (LString t)) = t
repVal t = renderCompactText t
repTerm (TLitString t) = t
repTerm t = renderCompactText t
alternate (x:xs) ys = x : alternate ys xs
alternate _ _ = []
formatLegacyArgs = do
let args = repTerm <$> V.toList es
!totalArgLen = sum (T.length <$> args)
inputLength = T.length s
unlessExecutionFlagSet FlagDisablePact44 $ computeGas (Right i) (GConcatenation inputLength totalArgLen)
pure args
formatFullGassedArgs = do
vals <- traverse enforcePactValue es
void $ computeGas (Right i) (GFormatValues s vals)