-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathaddressGenerator.go
More file actions
77 lines (61 loc) · 2.45 KB
/
addressGenerator.go
File metadata and controls
77 lines (61 loc) · 2.45 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
package addressGenerator
import (
"encoding/binary"
"github.com/ElrondNetwork/elrond-go-core/core"
"github.com/ElrondNetwork/elrond-go-core/core/check"
"github.com/ElrondNetwork/elrond-go-core/hashing"
"github.com/ElrondNetwork/elrond-go-core/hashing/keccak"
)
// addressGenerator is used to generate some addresses based on elrond-go logic
type addressGenerator struct {
pubkeyConv core.PubkeyConverter
hasher hashing.Hasher
}
// NewAddressGenerator will create an address generator instance
func NewAddressGenerator(pubkeyConv core.PubkeyConverter) (*addressGenerator, error) {
if check.IfNil(pubkeyConv) {
return nil, core.ErrNilPubkeyConverter
}
return &addressGenerator{
pubkeyConv: pubkeyConv,
hasher: keccak.NewKeccak(),
}, nil
}
// NewAddress is a hook which creates a new smart contract address from the creators address and nonce
// The address is created by applied keccak256 on the appended value off creator address and nonce
// Prefix mask is applied for first 8 bytes 0, and for bytes 9-10 - VM type
// Suffix mask is applied - last 2 bytes are for the shard ID - mask is applied as suffix mask
func (ag *addressGenerator) NewAddress(creatorAddress []byte, creatorNonce uint64, vmType []byte) ([]byte, error) {
addressLength := ag.pubkeyConv.Len()
if len(creatorAddress) != addressLength {
return nil, ErrAddressLengthNotCorrect
}
if len(vmType) != core.VMTypeLen {
return nil, ErrVMTypeLengthIsNotCorrect
}
base := hashFromAddressAndNonce(creatorAddress, creatorNonce)
prefixMask := createPrefixMask(vmType)
suffixMask := createSuffixMask(creatorAddress)
copy(base[:core.NumInitCharactersForScAddress], prefixMask)
copy(base[len(base)-core.ShardIdentiferLen:], suffixMask)
return base, nil
}
// IsInterfaceNil returns true if there is no value under the interface
func (ag *addressGenerator) IsInterfaceNil() bool {
return ag == nil
}
func hashFromAddressAndNonce(creatorAddress []byte, creatorNonce uint64) []byte {
buffNonce := make([]byte, 8)
binary.LittleEndian.PutUint64(buffNonce, creatorNonce)
adrAndNonce := append(creatorAddress, buffNonce...)
scAddress := keccak.NewKeccak().Compute(string(adrAndNonce))
return scAddress
}
func createPrefixMask(vmType []byte) []byte {
prefixMask := make([]byte, core.NumInitCharactersForScAddress-core.VMTypeLen)
prefixMask = append(prefixMask, vmType...)
return prefixMask
}
func createSuffixMask(creatorAddress []byte) []byte {
return creatorAddress[len(creatorAddress)-2:]
}