-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpack.go
48 lines (45 loc) · 1.22 KB
/
pack.go
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
package ethdial
import (
"errors"
"math/big"
"strconv"
)
func EnPack(numb []*big.Int, span []int) (*big.Int, error) {
// pack big.Ints into a 256-bit pack
// []numb are the collection of big.ints
// []span are the number of bytes each big.int occupies
var err error
pack := new(big.Int)
if len(numb) == len(span) {
for i := range numb {
modu := 1 << uint(8*span[i])
if numb[i].Cmp(big.NewInt(int64(modu))) == 1 {
err = errors.New(numb[i].String() + " is larger than 2^" + strconv.Itoa(8*span[i]) + " (" + strconv.Itoa(modu) + ")")
break
}
pack.Mul(pack, big.NewInt(int64(modu)))
pack.Add(pack, big.NewInt(numb[i].Int64()))
}
} else {
err = errors.New("lengths do not match")
}
return pack, err
}
func UnPack(pack *big.Int, span []int) ([]*big.Int, error) {
// unpack big.Ints from a 256-bit pack
// []span are the number of bytes each int occupies
var err error
var numb []*big.Int
if len(span) > 0 {
for i := range span {
remn := new(big.Int).Set(pack)
modu := big.NewInt(int64(1 << uint(8*span[len(span)-1-i])))
remn.Mod(remn, modu)
numb = append([]*big.Int{remn}, numb...)
pack.Div(pack, modu)
}
} else {
err = errors.New("length of spans is nil")
}
return numb, err
}