From 5d4739135096fa294605b465bedb9022db0968af Mon Sep 17 00:00:00 2001 From: Albert Le Batteux Date: Mon, 27 Mar 2023 18:36:16 +0100 Subject: [PATCH] feat(stdlibs): import crypto/sha256 (#580) --- stdlibs/crypto/sha256/sha256.gno | 12 ++++++++++ stdlibs/crypto/sha256/sha256_test.gno | 17 ++++++++++++++ stdlibs/internal/crypto/sha256/sha256.gno | 3 +++ stdlibs/stdlibs.go | 28 +++++++++++++++++++++++ 4 files changed, 60 insertions(+) create mode 100644 stdlibs/crypto/sha256/sha256.gno create mode 100644 stdlibs/crypto/sha256/sha256_test.gno create mode 100644 stdlibs/internal/crypto/sha256/sha256.gno diff --git a/stdlibs/crypto/sha256/sha256.gno b/stdlibs/crypto/sha256/sha256.gno new file mode 100644 index 00000000000..efb8ebb8e37 --- /dev/null +++ b/stdlibs/crypto/sha256/sha256.gno @@ -0,0 +1,12 @@ +package sha256 + +import ( + isha256 "internal/crypto/sha256" +) + +const Size = 32 + +// Sum returns the SHA-256 checksum of the data. +func Sum256(data []byte) [Size]byte { + return isha256.Sum256(data) +} diff --git a/stdlibs/crypto/sha256/sha256_test.gno b/stdlibs/crypto/sha256/sha256_test.gno new file mode 100644 index 00000000000..2522d822307 --- /dev/null +++ b/stdlibs/crypto/sha256/sha256_test.gno @@ -0,0 +1,17 @@ +package sha256 + +import ( + "crypto/sha256" + "encoding/hex" + "std" + "testing" +) + +func TestSha256Sum(t *testing.T) { + got := sha256.Sum256([]byte("sha256 this string"))[:] + expected := "1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a0d3db739d77aacb" + + if hex.EncodeToString(got) != expected { + t.Errorf("got %v(%T), expected %v(%T)", hex.EncodeToString(got), got, expected, expected) + } +} diff --git a/stdlibs/internal/crypto/sha256/sha256.gno b/stdlibs/internal/crypto/sha256/sha256.gno new file mode 100644 index 00000000000..458b2123f59 --- /dev/null +++ b/stdlibs/internal/crypto/sha256/sha256.gno @@ -0,0 +1,3 @@ +package sha256 + +// XXX injected via stdlibs/stdlibs.go diff --git a/stdlibs/stdlibs.go b/stdlibs/stdlibs.go index b365e43a14e..44bd05664f5 100644 --- a/stdlibs/stdlibs.go +++ b/stdlibs/stdlibs.go @@ -1,6 +1,7 @@ package stdlibs import ( + "crypto/sha256" "math" "reflect" "strconv" @@ -20,6 +21,33 @@ func InjectNativeMappings(store gno.Store) { func InjectPackage(store gno.Store, pn *gno.PackageNode) { switch pn.PkgPath { + case "internal/crypto/sha256": + pn.DefineNative("Sum256", + gno.Flds( // params + "data", "[]byte", + ), + gno.Flds( // results + "bz", "[32]byte", + ), + func(m *gno.Machine) { + arg0 := m.LastBlock().GetParams1().TV + bz := []byte(nil) + + if arg0.V != nil { + slice := arg0.V.(*gno.SliceValue) + array := slice.GetBase(m.Store) + bz = array.GetReadonlyBytes()[:slice.Length] + } + + hash := sha256.Sum256(bz) + res0 := gno.Go2GnoValue( + m.Alloc, + m.Store, + reflect.ValueOf(hash), + ) + m.PushValue(res0) + }, + ) case "internal/math": pn.DefineNative("Float32bits", gno.Flds( // params