Skip to content

Commit

Permalink
feat(stdlibs): import crypto/sha256 (#580)
Browse files Browse the repository at this point in the history
  • Loading branch information
albttx authored and peter7891 committed Mar 29, 2023
1 parent 23f8068 commit 5d47391
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 0 deletions.
12 changes: 12 additions & 0 deletions stdlibs/crypto/sha256/sha256.gno
Original file line number Diff line number Diff line change
@@ -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)
}
17 changes: 17 additions & 0 deletions stdlibs/crypto/sha256/sha256_test.gno
Original file line number Diff line number Diff line change
@@ -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)
}
}
3 changes: 3 additions & 0 deletions stdlibs/internal/crypto/sha256/sha256.gno
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package sha256

// XXX injected via stdlibs/stdlibs.go
28 changes: 28 additions & 0 deletions stdlibs/stdlibs.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package stdlibs

import (
"crypto/sha256"
"math"
"reflect"
"strconv"
Expand All @@ -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
Expand Down

0 comments on commit 5d47391

Please sign in to comment.