From 51cebe9e4714996ffba61aec7d1a5e0912bf5d3c Mon Sep 17 00:00:00 2001 From: Evgenii Stratonikov Date: Fri, 21 Aug 2020 09:30:07 +0300 Subject: [PATCH] smartcontract: support creation of majority multisig scripts --- pkg/smartcontract/contract.go | 8 ++++++ pkg/smartcontract/contract_test.go | 45 ++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/pkg/smartcontract/contract.go b/pkg/smartcontract/contract.go index 6a81896ae..6a88fe07b 100644 --- a/pkg/smartcontract/contract.go +++ b/pkg/smartcontract/contract.go @@ -44,3 +44,11 @@ func CreateDefaultMultiSigRedeemScript(publicKeys keys.PublicKeys) ([]byte, erro m := n - (n-1)/3 return CreateMultiSigRedeemScript(m, publicKeys) } + +// CreateMajorityMultiSigRedeemScript creates an "m out of n" type verification script +// using publicKeys length with m set to majority. +func CreateMajorityMultiSigRedeemScript(publicKeys keys.PublicKeys) ([]byte, error) { + n := len(publicKeys) + m := n - (n-1)/2 + return CreateMultiSigRedeemScript(m, publicKeys) +} diff --git a/pkg/smartcontract/contract_test.go b/pkg/smartcontract/contract_test.go index abcd20c8a..0be9d2b58 100644 --- a/pkg/smartcontract/contract_test.go +++ b/pkg/smartcontract/contract_test.go @@ -83,3 +83,48 @@ func TestCreateDefaultMultiSigRedeemScript(t *testing.T) { } checkM(7) } + +func TestCreateMajorityMultiSigRedeemScript(t *testing.T) { + var validators = make([]*keys.PublicKey, 0) + + var addKey = func() { + key, err := keys.NewPrivateKey() + require.NoError(t, err) + validators = append(validators, key.PublicKey()) + } + var checkM = func(m int) { + validScript, err := CreateMultiSigRedeemScript(m, validators) + require.NoError(t, err) + defaultScript, err := CreateMajorityMultiSigRedeemScript(validators) + require.NoError(t, err) + require.Equal(t, validScript, defaultScript) + } + + // 1 out of 1 + addKey() + checkM(1) + + // 2 out of 2 + addKey() + checkM(2) + + // 3 out of 4 + addKey() + addKey() + checkM(3) + + // 4 out of 6 + addKey() + addKey() + checkM(4) + + // 5 out of 8 + addKey() + addKey() + checkM(5) + + // 6 out of 10 + addKey() + addKey() + checkM(6) +}