From ba1195a6dbb6bb9a23c9377913e488522a7208a2 Mon Sep 17 00:00:00 2001 From: Benjamin DENEUX Date: Tue, 21 Feb 2023 15:02:50 +0100 Subject: [PATCH] feat(logic): bech32_address/3 predicate conversion in one way --- x/logic/interpreter/registry.go | 1 + x/logic/predicate/address.go | 27 +++++++++++++++++++++++++++ 2 files changed, 28 insertions(+) create mode 100644 x/logic/predicate/address.go diff --git a/x/logic/interpreter/registry.go b/x/logic/interpreter/registry.go index 6dfefb64..c820bce5 100644 --- a/x/logic/interpreter/registry.go +++ b/x/logic/interpreter/registry.go @@ -117,6 +117,7 @@ var Registry = map[string]RegistryEntry{ "did_components/2": {predicate.DIDComponents, 1}, "sha_hash/2": {predicate.SHAHash, 1}, "hex_bytes/2": {predicate.HexBytes, 1}, + "bech32_address/3": {predicate.Bech32Address, 1}, } // RegistryNames is the list of the predicate names in the Registry. diff --git a/x/logic/predicate/address.go b/x/logic/predicate/address.go new file mode 100644 index 00000000..e0dc837f --- /dev/null +++ b/x/logic/predicate/address.go @@ -0,0 +1,27 @@ +package predicate + +import ( + "context" + "fmt" + + bech322 "github.com/cosmos/cosmos-sdk/types/bech32" + "github.com/ichiban/prolog/engine" + "github.com/okp4/okp4d/x/logic/util" +) + +func Bech32Address(vm *engine.VM, hrp, address, bech32 engine.Term, cont engine.Cont, env *engine.Env) *engine.Promise { + return engine.Delay(func(ctx context.Context) *engine.Promise { + switch b := env.Resolve(bech32).(type) { + case engine.Variable: + return nil + case engine.Atom: + h, a, err := bech322.DecodeAndConvert(b.String()) + if err != nil { + return engine.Error(fmt.Errorf("bech32_address/3: failed convert bech32 encoded string to base64: %w", err)) + } + return engine.Unify(vm, Tuple(hrp, address), Tuple(util.StringToTerm(h), BytesToList(a)), cont, env) + default: + return engine.Error(fmt.Errorf("bech32_address/3: invalid data type: %T, should be Atom or Variable", b)) + } + }) +}