Skip to content

Commit

Permalink
Merge pull request #4716 from multiversx/feat/pubkeyconverter-refactor
Browse files Browse the repository at this point in the history
Feat/pubkeyconverter_refactor
  • Loading branch information
schimih authored Mar 20, 2023
2 parents 89b54e7 + 3848ddb commit e272723
Show file tree
Hide file tree
Showing 134 changed files with 931 additions and 985 deletions.
1 change: 1 addition & 0 deletions cmd/keygenerator/converter/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ package converter

import "errors"

// ErrNotImplemented is returned when a method is not implemented
var errNotImplemented = errors.New("not implemented")
15 changes: 3 additions & 12 deletions cmd/keygenerator/converter/pidPubkeyConverter.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
package converter

import (
"encoding/hex"
"runtime/debug"

crypto "github.com/multiversx/mx-chain-crypto-go"
"github.com/multiversx/mx-chain-crypto-go/signing"
"github.com/multiversx/mx-chain-crypto-go/signing/secp256k1"
Expand Down Expand Up @@ -33,19 +30,13 @@ func (converter *pidPubkeyConverter) Decode(_ string) ([]byte, error) {
}

// Encode encodes a byte array in its string representation
func (converter *pidPubkeyConverter) Encode(pkBytes []byte) string {
func (converter *pidPubkeyConverter) Encode(pkBytes []byte) (string, error) {
pidString, err := converter.encode(pkBytes)
if err != nil {
log.Warn("pidPubkeyConverter.Encode encode",
"hex buff", hex.EncodeToString(pkBytes),
"error", err,
"stack trace", string(debug.Stack()),
)

return ""
return "", err
}

return pidString
return pidString, nil
}

func (converter *pidPubkeyConverter) encode(pkBytes []byte) (string, error) {
Expand Down
6 changes: 4 additions & 2 deletions cmd/keygenerator/converter/pidPubkeyConverter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ func TestPidPubkeyConverter_Encode(t *testing.T) {
}
}()

encoded := converter.Encode([]byte("not a valid PK"))
encoded, err := converter.Encode([]byte("not a valid PK"))
assert.Contains(t, err.Error(), "parameter is invalid")
assert.Empty(t, encoded)
})
t.Run("valid public key should work", func(t *testing.T) {
Expand All @@ -40,7 +41,8 @@ func TestPidPubkeyConverter_Encode(t *testing.T) {
pkBytes, err := hex.DecodeString(pkHex)
assert.Nil(t, err)

encoded := converter.Encode(pkBytes)
encoded, err := converter.Encode(pkBytes)
assert.Nil(t, err)
assert.Equal(t, "16Uiu2HAmSHgyTYyawhsZv9opxTHX77vKjoPeGkyCYS5fYVMssHjN", encoded)
})
}
Expand Down
10 changes: 7 additions & 3 deletions cmd/keygenerator/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ const minedWalletPrefixKeys = "mined-wallet"
const nopattern = "nopattern"
const desiredpattern = "[0-f]+"
const noshard = -1
const pubkeyHrp = "erd"

type key struct {
skBytes []byte
Expand All @@ -49,7 +50,7 @@ type key struct {

type pubKeyConverter interface {
Decode(humanReadable string) ([]byte, error)
Encode(pkBytes []byte) string
Encode(pkBytes []byte) (string, error)
IsInterfaceNil() bool
}

Expand Down Expand Up @@ -132,7 +133,7 @@ VERSION:

validatorPubKeyConverter, _ = pubkeyConverter.NewHexPubkeyConverter(blsPubkeyLen)
pidPubKeyConverter = converter.NewPidPubkeyConverter()
walletPubKeyConverter, _ = pubkeyConverter.NewBech32PubkeyConverter(txSignPubkeyLen, log)
walletPubKeyConverter, _ = pubkeyConverter.NewBech32PubkeyConverter(txSignPubkeyLen, pubkeyHrp)
)

func main() {
Expand Down Expand Up @@ -365,7 +366,10 @@ func writeKeyToStream(writer io.Writer, key key, converter pubKeyConverter) erro
return fmt.Errorf("nil writer")
}

pkString := converter.Encode(key.pkBytes)
pkString, err := converter.Encode(key.pkBytes)
if err != nil {
return err
}

blk := pem.Block{
Type: "PRIVATE KEY for " + pkString,
Expand Down
1 change: 1 addition & 0 deletions cmd/node/config/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -601,6 +601,7 @@
Length = 32
Type = "bech32"
SignatureLength = 64
Hrp = "erd"

[ValidatorPubkeyConverter]
Length = 96
Expand Down
5 changes: 1 addition & 4 deletions common/factory/pubkeyConverterFactory.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,8 @@ import (
"github.com/multiversx/mx-chain-core-go/core/pubkeyConverter"
"github.com/multiversx/mx-chain-go/config"
"github.com/multiversx/mx-chain-go/state"
logger "github.com/multiversx/mx-chain-logger-go"
)

var log = logger.GetOrCreate("state/factory")

// HexFormat defines the hex format for the pubkey converter
const HexFormat = "hex"

Expand All @@ -24,7 +21,7 @@ func NewPubkeyConverter(config config.PubkeyConfig) (core.PubkeyConverter, error
case HexFormat:
return pubkeyConverter.NewHexPubkeyConverter(config.Length)
case Bech32Format:
return pubkeyConverter.NewBech32PubkeyConverter(config.Length, log)
return pubkeyConverter.NewBech32PubkeyConverter(config.Length, config.Hrp)
default:
return nil, fmt.Errorf("%w unrecognized type %s", state.ErrInvalidPubkeyConverterType, config.Type)
}
Expand Down
4 changes: 3 additions & 1 deletion common/factory/pubkeyConverterFactory_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,13 @@ func TestNewPubkeyConverter_Bech32ShouldWork(t *testing.T) {
config.PubkeyConfig{
Length: 32,
Type: "bech32",
Hrp: "erd",
},
)

assert.Nil(t, err)
expected, _ := pubkeyConverter.NewBech32PubkeyConverter(32, log)
expected, err := pubkeyConverter.NewBech32PubkeyConverter(32, "erd")
assert.Nil(t, err)
assert.IsType(t, expected, pc)
}

Expand Down
1 change: 1 addition & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ type PubkeyConfig struct {
Length int
Type string
SignatureLength int
Hrp string
}

// TypeConfig will map the string type configuration
Expand Down
4 changes: 2 additions & 2 deletions config/tomlConfig_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -611,7 +611,7 @@ func TestEnableEpochConfig(t *testing.T) {
# ESDTNFTCreateOnMultiShardEnableEpoch represents the epoch when esdt nft creation on multiple shards is enabled
ESDTNFTCreateOnMultiShardEnableEpoch = 39
# MetaESDTSetEnableEpoch represents the epoch when the backward compatibility for save key value error is enabled
MetaESDTSetEnableEpoch = 40
Expand Down Expand Up @@ -694,7 +694,7 @@ func TestEnableEpochConfig(t *testing.T) {
{EnableEpoch = 0, Type = "no-KOSK"},
{EnableEpoch = 3, Type = "KOSK"}
]
[GasSchedule]
GasScheduleByEpochs = [
{ StartEpoch = 46, FileName = "gasScheduleV1.toml" },
Expand Down
4 changes: 2 additions & 2 deletions dataRetriever/factory/dataPoolFactory_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,15 +86,15 @@ func TestNewDataPoolFromConfig_BadConfigShouldErr(t *testing.T) {
require.Nil(t, holder)
fmt.Println(err)
require.NotNil(t, err)
require.True(t, strings.Contains(err.Error(), "Must provide a positive size while creating the cache for the miniblocks"))
require.True(t, strings.Contains(err.Error(), "must provide a positive size while creating the cache for the miniblocks"))

args = getGoodArgs()
args.Config.PeerBlockBodyDataPool.Capacity = 0
holder, err = NewDataPoolFromConfig(args)
require.Nil(t, holder)
fmt.Println(err)
require.NotNil(t, err)
require.True(t, strings.Contains(err.Error(), "Must provide a positive size while creating the cache for the peer mini block body"))
require.True(t, strings.Contains(err.Error(), "must provide a positive size while creating the cache for the peer mini block body"))

args = getGoodArgs()
args.Config.TrieSyncStorage.Capacity = 0
Expand Down
2 changes: 1 addition & 1 deletion epochStart/bootstrap/process_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ func createComponentsForEpochStart() (*mock.CoreComponentsMock, *mock.CryptoComp
Hash: &hashingMocks.HasherMock{},
TxSignHasherField: &hashingMocks.HasherMock{},
UInt64ByteSliceConv: &mock.Uint64ByteSliceConverterMock{},
AddrPubKeyConv: &mock.PubkeyConverterMock{},
AddrPubKeyConv: &testscommon.PubkeyConverterMock{},
PathHdl: &testscommon.PathManagerStub{},
EpochNotifierField: &epochNotifier.EpochNotifierStub{},
TxVersionCheckField: versioning.NewTxVersionChecker(1),
Expand Down
2 changes: 1 addition & 1 deletion epochStart/bootstrap/syncEpochStartMeta_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ func getEpochStartSyncerArgs() ArgsNewEpochStartMetaSyncer {
Marsh: &mock.MarshalizerMock{},
Hash: &hashingMocks.HasherMock{},
UInt64ByteSliceConv: &mock.Uint64ByteSliceConverterMock{},
AddrPubKeyConv: mock.NewPubkeyConverterMock(32),
AddrPubKeyConv: testscommon.NewPubkeyConverterMock(32),
PathHdl: &testscommon.PathManagerStub{},
ChainIdCalled: func() string {
return "chain-ID"
Expand Down
2 changes: 1 addition & 1 deletion epochStart/metachain/baseRewards_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1150,7 +1150,7 @@ func getBaseRewardsArguments() BaseRewardsCreatorArgs {

return BaseRewardsCreatorArgs{
ShardCoordinator: shardCoordinator,
PubkeyConverter: mock.NewPubkeyConverterMock(32),
PubkeyConverter: testscommon.NewPubkeyConverterMock(32),
RewardsStorage: mock.NewStorerMock(),
MiniBlockStorage: mock.NewStorerMock(),
Hasher: &hashingMocks.HasherMock{},
Expand Down
4 changes: 2 additions & 2 deletions epochStart/metachain/systemSCs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -930,7 +930,7 @@ func createFullArgumentsForSystemSCProcessing(enableEpochsConfig config.EnableEp
ShardCoordinator: &mock.ShardCoordinatorStub{},
DataPool: &dataRetrieverMock.PoolsHolderStub{},
StorageService: &storageStubs.ChainStorerStub{},
PubkeyConv: &mock.PubkeyConverterMock{},
PubkeyConv: &testscommon.PubkeyConverterMock{},
PeerAdapter: peerAccountsDB,
Rater: &mock.RaterStub{},
RewardsHandler: &mock.RewardsHandlerStub{},
Expand All @@ -954,7 +954,7 @@ func createFullArgumentsForSystemSCProcessing(enableEpochsConfig config.EnableEp

argsHook := hooks.ArgBlockChainHook{
Accounts: userAccountsDB,
PubkeyConv: &mock.PubkeyConverterMock{},
PubkeyConv: &testscommon.PubkeyConverterMock{},
StorageService: &storageStubs.ChainStorerStub{},
BlockChain: blockChain,
ShardCoordinator: &mock.ShardCoordinatorStub{},
Expand Down
37 changes: 0 additions & 37 deletions epochStart/mock/pubkeyConverterMock.go

This file was deleted.

56 changes: 35 additions & 21 deletions examples/address_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ func TestHexAddressToBech32Address(t *testing.T) {
hexEncodedAddressBytes, err := hex.DecodeString(hexEncodedAddress)
require.NoError(t, err)

bech32Address := addressEncoder.Encode(hexEncodedAddressBytes)
bech32Address, err := addressEncoder.Encode(hexEncodedAddressBytes)
require.NoError(t, err)
require.Equal(t, "erd14uqxan5rgucsf6537ll4vpwyc96z7us5586xhc5euv8w96rsw95sfl6a49", bech32Address)
}

Expand Down Expand Up @@ -61,20 +62,31 @@ func computeShardID(t *testing.T, addressBech32 string, shardCoordinator shardin
}

func TestSystemSCsAddressesAndSpecialAddresses(t *testing.T) {
contractDeployScAdress := addressEncoder.Encode(make([]byte, addressEncoder.Len()))
stakingScAddress := addressEncoder.Encode(vm.StakingSCAddress)
validatorScAddress := addressEncoder.Encode(vm.ValidatorSCAddress)
esdtScAddress := addressEncoder.Encode(vm.ESDTSCAddress)
governanceScAddress := addressEncoder.Encode(vm.GovernanceSCAddress)
jailingAddress := addressEncoder.Encode(vm.JailingAddress)
endOfEpochAddress := addressEncoder.Encode(vm.EndOfEpochAddress)
delegationManagerScAddress := addressEncoder.Encode(vm.DelegationManagerSCAddress)
firstDelegationScAddress := addressEncoder.Encode(vm.FirstDelegationSCAddress)
contractDeployScAdress, err := addressEncoder.Encode(make([]byte, addressEncoder.Len()))
require.NoError(t, err)
stakingScAddress, err := addressEncoder.Encode(vm.StakingSCAddress)
require.NoError(t, err)
validatorScAddress, err := addressEncoder.Encode(vm.ValidatorSCAddress)
require.NoError(t, err)
esdtScAddress, err := addressEncoder.Encode(vm.ESDTSCAddress)
require.NoError(t, err)
governanceScAddress, err := addressEncoder.Encode(vm.GovernanceSCAddress)
require.NoError(t, err)
jailingAddress, err := addressEncoder.Encode(vm.JailingAddress)
require.NoError(t, err)
endOfEpochAddress, err := addressEncoder.Encode(vm.EndOfEpochAddress)
require.NoError(t, err)
delegationManagerScAddress, err := addressEncoder.Encode(vm.DelegationManagerSCAddress)
require.NoError(t, err)
firstDelegationScAddress, err := addressEncoder.Encode(vm.FirstDelegationSCAddress)
require.NoError(t, err)

genesisMintingAddressBytes, err := hex.DecodeString("f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0")
require.NoError(t, err)
genesisMintingAddress := addressEncoder.Encode(genesisMintingAddressBytes)
systemAccountAddress := addressEncoder.Encode(core.SystemAccountAddress)
genesisMintingAddress, err := addressEncoder.Encode(genesisMintingAddressBytes)
require.NoError(t, err)
systemAccountAddress, err := addressEncoder.Encode(core.SystemAccountAddress)
require.NoError(t, err)

esdtGlobalSettingsAddresses := getGlobalSettingsAddresses()

Expand Down Expand Up @@ -116,19 +128,21 @@ func TestSystemSCsAddressesAndSpecialAddresses(t *testing.T) {
}

func getGlobalSettingsAddresses() map[uint32]string {
computeAddress := func(shardID uint32) string {
baseSystemAccountAddress := core.SystemAccountAddress
globalSettingsAddress := baseSystemAccountAddress
globalSettingsAddress[len(globalSettingsAddress)-1] = uint8(shardID)

return addressEncoder.Encode(globalSettingsAddress)
}

numShards := uint32(3)
addressesMap := make(map[uint32]string, numShards)
for i := uint32(0); i < numShards; i++ {
addressesMap[i] = computeAddress(i)
addressesMap[i] = computeGlobalSettingsAddr(i)
}

return addressesMap
}

func computeGlobalSettingsAddr(shardID uint32) string {
baseSystemAccountAddress := core.SystemAccountAddress
globalSettingsAddress := baseSystemAccountAddress
globalSettingsAddress[len(globalSettingsAddress)-1] = uint8(shardID)

computedAddress, _ := addressEncoder.Encode(globalSettingsAddress)

return computedAddress
}
3 changes: 1 addition & 2 deletions examples/construction_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"math/big"
"testing"

"github.com/multiversx/mx-chain-core-go/core/mock"
"github.com/multiversx/mx-chain-core-go/core/pubkeyConverter"
"github.com/multiversx/mx-chain-core-go/data/block"
"github.com/multiversx/mx-chain-core-go/data/transaction"
Expand All @@ -20,7 +19,7 @@ import (
)

var (
addressEncoder, _ = pubkeyConverter.NewBech32PubkeyConverter(32, &mock.LoggerMock{})
addressEncoder, _ = pubkeyConverter.NewBech32PubkeyConverter(32, "erd")
signingMarshalizer = &marshal.JsonMarshalizer{}
signer = &singlesig.Ed25519Signer{}
signingCryptoSuite = ed25519.NewEd25519()
Expand Down
5 changes: 4 additions & 1 deletion examples/messageSign_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,10 @@ func signMessage(t *testing.T, senderSeedHex string, message string) (string, st
publicKeyBytes, err := publicKey.ToByteArray()
require.NoError(t, err)

return addressEncoder.Encode(publicKeyBytes), hex.EncodeToString(hash), hex.EncodeToString(signature)
address, err := addressEncoder.Encode(publicKeyBytes)
require.NoError(t, err)

return address, hex.EncodeToString(hash), hex.EncodeToString(signature)
}

func computeHashForMessage(message string) []byte {
Expand Down
1 change: 1 addition & 0 deletions facade/nodeFacade.go
Original file line number Diff line number Diff line change
Expand Up @@ -680,6 +680,7 @@ func (nf *nodeFacade) convertVmOutputToApiResponse(input *vmcommon.VMOutput) *vm
// GetGenesisNodesPubKeys will return genesis nodes public keys by shard
func (nf *nodeFacade) GetGenesisNodesPubKeys() (map[uint32][]string, map[uint32][]string, error) {
eligible, waiting := nf.apiResolver.GetGenesisNodesPubKeys()

if eligible == nil && waiting == nil {
return nil, nil, ErrNilGenesisNodes
}
Expand Down
Loading

0 comments on commit e272723

Please sign in to comment.