Skip to content
This repository has been archived by the owner on Aug 18, 2020. It is now read-only.

[CO-410] Introduce NetworkMagic #3733

Merged
merged 2 commits into from
Oct 17, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 12 additions & 7 deletions auxx/src/Command/Proc.hs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import Pos.Core (AddrStakeDistribution (..), StakeholderId,
addressHash, mkMultiKeyDistr, unsafeGetCoin)
import Pos.Core.Common (AddrAttributes (..), AddrSpendingData (..),
makeAddress)
import Pos.Core.NetworkMagic (NetworkMagic (..))
import Pos.Crypto (PublicKey, emptyPassphrase, encToPublic,
fullPublicKeyF, hashHexF, noPassEncrypt, safeCreatePsk,
unsafeCheatingHashCoerce, withSafeSigner)
Expand Down Expand Up @@ -114,9 +115,9 @@ createCommandProcs mCoreConfig mTxpConfig hasAuxxMode printAction mDiffusion = r
, cpExec = \(pk', mDistr) -> do
pk <- toLeft pk'
addr <- case mDistr of
Nothing -> makePubKeyAddressAuxx (configEpochSlots genesisConfig) pk
Nothing -> makePubKeyAddressAuxx fixedNM (configEpochSlots genesisConfig) pk
Just distr -> return $
makeAddress (PubKeyASD pk) (AddrAttributes Nothing distr)
makeAddress (PubKeyASD pk) (AddrAttributes Nothing distr fixedNM)
return $ ValueAddress addr
, cpHelp = "address for the specified public key. a stake distribution \
\ can be specified manually (by default it uses the current epoch \
Expand All @@ -135,7 +136,7 @@ createCommandProcs mCoreConfig mTxpConfig hasAuxxMode printAction mDiffusion = r
sk <- evaluateWHNF (sks !! i) -- WHNF is sufficient to force possible errors
-- from using (!!). I'd use NF but there's no
-- NFData instance for secret keys.
addrHD <- deriveHDAddressAuxx (configEpochSlots genesisConfig) sk
addrHD <- deriveHDAddressAuxx fixedNM (configEpochSlots genesisConfig) sk
return $ ValueAddress addrHD
, cpHelp = "address of the HD wallet for the specified public key"
},
Expand Down Expand Up @@ -200,7 +201,7 @@ createCommandProcs mCoreConfig mTxpConfig hasAuxxMode printAction mDiffusion = r
, cpArgumentConsumer = getArg (tyAddress `tyEither` tyPublicKey `tyEither` tyInt) "addr"
, cpExec = \addr' -> do
addr <-
either return (makePubKeyAddressAuxx $ configEpochSlots genesisConfig) <=<
either return (makePubKeyAddressAuxx fixedNM $ configEpochSlots genesisConfig) <=<
traverse (either return getPublicKeyFromIndex) $ addr'
balance <- getBalance (configGenesisData genesisConfig) addr
return $ ValueNumber (fromIntegral . unsafeGetCoin $ balance)
Expand Down Expand Up @@ -498,8 +499,8 @@ createCommandProcs mCoreConfig mTxpConfig hasAuxxMode printAction mDiffusion = r
printAction "Available addresses:"
for_ (zip [0 :: Int ..] sks) $ \(i, sk) -> do
let pk = encToPublic sk
addr <- makePubKeyAddressAuxx epochSlots pk
addrHD <- deriveHDAddressAuxx epochSlots sk
addr <- makePubKeyAddressAuxx fixedNM epochSlots pk
addrHD <- deriveHDAddressAuxx fixedNM epochSlots sk
printAction $
sformat (" #"%int%": addr: "%build%"\n"%
" pk: "%fullPublicKeyF%"\n"%
Expand All @@ -508,7 +509,7 @@ createCommandProcs mCoreConfig mTxpConfig hasAuxxMode printAction mDiffusion = r
i addr pk (addressHash pk) addrHD
walletMB <- (^. usWallet) <$> (view userSecret >>= readTVarIO)
whenJust walletMB $ \wallet -> do
addrHD <- deriveHDAddressAuxx epochSlots (_wusRootKey wallet)
addrHD <- deriveHDAddressAuxx fixedNM epochSlots (_wusRootKey wallet)
printAction $
sformat (" Wallet address:\n"%
" HD addr: "%build)
Expand Down Expand Up @@ -565,3 +566,7 @@ getPublicKeyFromIndex i = do
let sk = sks !! i
pk = encToPublic sk
evaluateNF pk


fixedNM :: NetworkMagic
fixedNM = NetworkMainOrStage
12 changes: 9 additions & 3 deletions auxx/src/Command/Tx.hs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ import Pos.Core (IsBootstrapEraAddr (..), Timestamp (..),
deriveFirstHDAddress, makePubKeyAddress, mkCoin)
import Pos.Core.Conc (concurrently, currentTime, delay,
forConcurrently, modifySharedAtomic, newSharedAtomic)
import Pos.Core.NetworkMagic (NetworkMagic (..))
import Pos.Crypto (EncryptedSecretKey, SecretKey, emptyPassphrase,
encToPublic, fakeSigner, hash, safeToPublic, toPublic,
withSafeSigners)
Expand Down Expand Up @@ -116,14 +117,16 @@ sendToAllGenesis genesisConfig keysToSend diffusion (SendToAllGenesisParams gene
publicKey = toPublic secretKey
-- construct transaction output
outAddr <- makePubKeyAddressAuxx
fixedNM
(configEpochSlots genesisConfig)
publicKey
let txOut1 = TxOut {
txOutAddress = outAddr,
txOutValue = mkCoin 1
}
txOuts = TxOutAux txOut1 :| []
utxo <- getOwnUtxoForPk (configGenesisData genesisConfig)
utxo <- getOwnUtxoForPk
(configGenesisData genesisConfig)
$ safeToPublic signer
etx <- createTx genesisConfig mempty utxo signer txOuts publicKey
case etx of
Expand Down Expand Up @@ -232,10 +235,10 @@ send
send genesisConfig diffusion idx outputs = do
skey <- takeSecret
let curPk = encToPublic skey
let plainAddresses = map (flip makePubKeyAddress curPk . IsBootstrapEraAddr) [False, True]
let plainAddresses = map (flip (makePubKeyAddress fixedNM) curPk . IsBootstrapEraAddr) [False, True]
let (hdAddresses, hdSecrets) = unzip $ map
(\ibea -> fromMaybe (error "send: pass mismatch") $
deriveFirstHDAddress (IsBootstrapEraAddr ibea) emptyPassphrase skey) [False, True]
deriveFirstHDAddress fixedNM (IsBootstrapEraAddr ibea) emptyPassphrase skey) [False, True]
let allAddresses = hdAddresses ++ plainAddresses
let allSecrets = hdSecrets ++ [skey, skey]
etx <- withSafeSigners allSecrets (pure emptyPassphrase) $ \signers -> runExceptT @AuxxException $ do
Expand Down Expand Up @@ -283,3 +286,6 @@ sendTxsFromFile diffusion txsFile = do
(topsortTxAuxes txAuxes)
let submitOne = submitTxRaw diffusion
mapM_ submitOne sortedTxAuxes

fixedNM :: NetworkMagic
fixedNM = NetworkMainOrStage
30 changes: 20 additions & 10 deletions auxx/src/Mode.hs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import Pos.Core (Address, HasPrimaryKey (..), IsBootstrapEraAddr (..),
SlotCount, deriveFirstHDAddress, largestPubKeyAddressBoot,
largestPubKeyAddressSingleKey, makePubKeyAddress, siEpoch)
import Pos.Core.JsonLog (CanJsonLog (..))
import Pos.Core.NetworkMagic (NetworkMagic)
import Pos.Core.Reporting (HasMisbehaviorMetrics (..),
MonadReporting (..))
import Pos.Core.Slotting (HasSlottingVar (..), MonadSlotsData)
Expand Down Expand Up @@ -215,11 +216,11 @@ instance (HasConfigurations, HasCompileInfo) =>
MonadAddresses AuxxMode where
type AddrData AuxxMode = PublicKey
getNewAddress = makePubKeyAddressAuxx
getFakeChangeAddress pc = do
getFakeChangeAddress nm pc = do
epochIndex <- siEpoch <$> getCurrentSlotInaccurate pc
gsIsBootstrapEra epochIndex <&> \case
False -> largestPubKeyAddressBoot
True -> largestPubKeyAddressSingleKey
False -> largestPubKeyAddressBoot nm
True -> largestPubKeyAddressSingleKey nm

instance MonadKeysRead AuxxMode where
getPublic = getPublicDefault
Expand All @@ -243,17 +244,26 @@ instance HasConfigurations =>
-- | In order to create an 'Address' from a 'PublicKey' we need to
-- choose suitable stake distribution. We want to pick it based on
-- whether we are currently in bootstrap era.
makePubKeyAddressAuxx :: MonadAuxxMode m => SlotCount -> PublicKey -> m Address
makePubKeyAddressAuxx epochSlots pk = do
makePubKeyAddressAuxx ::
MonadAuxxMode m
=> NetworkMagic
-> SlotCount
-> PublicKey
-> m Address
makePubKeyAddressAuxx nm epochSlots pk = do
epochIndex <- siEpoch <$> getCurrentSlotInaccurate epochSlots
ibea <- IsBootstrapEraAddr <$> gsIsBootstrapEra epochIndex
pure $ makePubKeyAddress ibea pk
pure $ makePubKeyAddress nm ibea pk

-- | Similar to @makePubKeyAddressAuxx@ but create HD address.
deriveHDAddressAuxx
:: MonadAuxxMode m => SlotCount -> EncryptedSecretKey -> m Address
deriveHDAddressAuxx epochSlots hdwSk = do
deriveHDAddressAuxx ::
MonadAuxxMode m
=> NetworkMagic
-> SlotCount
-> EncryptedSecretKey
-> m Address
deriveHDAddressAuxx nm epochSlots hdwSk = do
epochIndex <- siEpoch <$> getCurrentSlotInaccurate epochSlots
ibea <- IsBootstrapEraAddr <$> gsIsBootstrapEra epochIndex
pure $ fst $ fromMaybe (error "makePubKeyHDAddressAuxx: pass mismatch") $
deriveFirstHDAddress ibea emptyPassphrase hdwSk
deriveFirstHDAddress nm ibea emptyPassphrase hdwSk
12 changes: 10 additions & 2 deletions chain/src/Pos/Chain/Genesis/Generate.hs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import Pos.Core.Common (Address, Coin, IsBootstrapEraAddr (..),
coinToInteger, deriveFirstHDAddress,
makePubKeyAddressBoot, mkCoin, sumCoins,
unsafeIntegerToCoin)
import Pos.Core.NetworkMagic (NetworkMagic (..))
import Pos.Core.ProtocolConstants (ProtocolConstants, vssMaxTTL,
vssMinTTL)
import Pos.Crypto (EncryptedSecretKey, ProtocolMagic, RedeemPublicKey,
Expand Down Expand Up @@ -175,19 +176,22 @@ generateGenesisData pm pc (GenesisInitializer{..}) realAvvmBalances = determinis
vssCerts <- mkVssCertificatesMap
<$> mapM (generateVssCert pm pc) richmenSecrets

let nm = fixedNM

-- Non AVVM balances
---- Addresses
let createAddressRich :: SecretKey -> Address
createAddressRich (toPublic -> pk) = makePubKeyAddressBoot pk
createAddressRich (toPublic -> pk) = makePubKeyAddressBoot nm pk
let createAddressPoor :: PoorSecret -> Address
createAddressPoor (PoorEncryptedSecret hdwSk) =
fst $
fromMaybe (error "generateGenesisData: pass mismatch") $
deriveFirstHDAddress
nm
(IsBootstrapEraAddr True)
emptyPassphrase
hdwSk
createAddressPoor (PoorSecret secret) = makePubKeyAddressBoot (toPublic secret)
createAddressPoor (PoorSecret secret) = makePubKeyAddressBoot nm (toPublic secret)
let richAddresses = map (createAddressRich . rsPrimaryKey) richmenSecrets
poorAddresses = map createAddressPoor poorsSecrets

Expand Down Expand Up @@ -317,3 +321,7 @@ genTestnetDistribution TestnetBalanceOptions {..} testBalance =

getShare :: Double -> Integer -> Integer
getShare sh n = round $ sh * fromInteger n


fixedNM :: NetworkMagic
fixedNM = NetworkMainOrStage
9 changes: 8 additions & 1 deletion chain/src/Pos/Chain/Txp/GenesisUtxo.hs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import Pos.Chain.Txp.Toil (Utxo, utxoToStakes)
import Pos.Chain.Txp.Tx (TxIn (..), TxOut (..))
import Pos.Chain.Txp.TxOutAux (TxOutAux (..))
import Pos.Core (Address, Coin, StakesMap, makeRedeemAddress)
import Pos.Core.NetworkMagic (NetworkMagic (..))
import Pos.Crypto (unsafeHash)


Expand All @@ -26,9 +27,12 @@ genesisStakes genesisData =
genesisUtxo :: GenesisData -> Utxo
genesisUtxo genesisData =
let
networkMagic :: NetworkMagic
networkMagic = fixedNM

preUtxo :: [(Address, Coin)]
preUtxo =
(first makeRedeemAddress <$> HM.toList
(first (makeRedeemAddress networkMagic) <$> HM.toList
(getGenesisAvvmBalances $ gdAvvmDistr genesisData)
)
<> (HM.toList $ getGenesisNonAvvmBalances $ gdNonAvvmBalances
Expand All @@ -40,3 +44,6 @@ genesisUtxo genesisData =
(TxInUtxo (unsafeHash addr) 0, TxOutAux (TxOut addr coin))
in
Map.fromList $ utxoEntry <$> preUtxo

fixedNM :: NetworkMagic
fixedNM = NetworkMainOrStage
6 changes: 6 additions & 0 deletions chain/src/Pos/Chain/Txp/Toil/Failure.hs
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,8 @@ data TxOutVerFailure
| TxOutUnknownAddressType Address
-- | Can't send to a redeem address
| TxOutRedeemAddressProhibited Address
-- | NetworkMagic's must match
| TxOutAddressBadNetworkMagic Address
deriving (Show, Eq, Generic, NFData)

instance Buildable TxOutVerFailure where
Expand All @@ -188,3 +190,7 @@ instance Buildable TxOutVerFailure where
build (TxOutRedeemAddressProhibited addr) =
bprint ("sends money to a redeem address ("
%addressF%"), this is prohibited") addr
build (TxOutAddressBadNetworkMagic addr) =
bprint ("sends money to an address with mismatched \
\NetworkMagic ("%addressF%"), this is prohibited")
addr
8 changes: 6 additions & 2 deletions chain/src/Pos/Chain/Txp/Toil/Logic.hs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ import Pos.Core (AddrAttributes (..), AddrStakeDistribution (..),
import Pos.Core.Common (integerToCoin)
import qualified Pos.Core.Common as Fee (TxFeePolicy (..),
calculateTxSizeLinear)
import Pos.Core.NetworkMagic (NetworkMagic (..))
import Pos.Crypto (ProtocolMagic, WithHash (..), hash)
import Pos.Util (liftEither)

Expand Down Expand Up @@ -144,12 +145,11 @@ verifyAndApplyTx ::
-> ExceptT ToilVerFailure UtxoM TxUndo
verifyAndApplyTx pm adoptedBVD lockedAssets curEpoch verifyVersions tx@(_, txAux) = do
whenLeft (checkTxAux txAux) (throwError . ToilInconsistentTxAux)
let ctx = Utxo.VTxContext verifyVersions fixedNM
vtur@VerifyTxUtxoRes {..} <- Utxo.verifyTxUtxo pm ctx lockedAssets txAux
liftEither $ verifyGState adoptedBVD curEpoch txAux vtur
lift $ applyTxToUtxo' tx
pure vturUndo
where
ctx = Utxo.VTxContext verifyVersions

isRedeemTx :: TxUndo -> Bool
isRedeemTx resolvedOuts = all isRedeemAddress inputAddresses
Expand Down Expand Up @@ -237,3 +237,7 @@ withTxId aux = (hash (taTx aux), aux)

applyTxToUtxo' :: (TxId, TxAux) -> UtxoM ()
applyTxToUtxo' (i, TxAux tx _) = Utxo.applyTxToUtxo (WithHash tx i)


fixedNM :: NetworkMagic
fixedNM = NetworkMainOrStage
14 changes: 10 additions & 4 deletions chain/src/Pos/Chain/Txp/Toil/Utxo/Functions.hs
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,10 @@ import Pos.Chain.Txp.TxWitness (TxInWitness (..), TxSigData (..),
import Pos.Chain.Txp.Undo (TxUndo)
import Pos.Core (AddrType (..), Address (..), integerToCoin,
isRedeemAddress, isUnknownAddressType, sumCoins)
import Pos.Core.Attributes (Attributes (attrRemain),
areAttributesKnown)
import Pos.Core.Common (checkPubKeyAddress, checkRedeemAddress,
checkScriptAddress)
import Pos.Core.Attributes (Attributes (..), areAttributesKnown)
import Pos.Core.Common (AddrAttributes (..), checkPubKeyAddress,
checkRedeemAddress, checkScriptAddress)
import Pos.Core.NetworkMagic (NetworkMagic)
import Pos.Crypto (SignTag (SignRedeemTx, SignTx), WithHash (..),
checkSig, hash, redeemCheckSig)
import Pos.Crypto.Configuration (ProtocolMagic)
Expand All @@ -59,6 +59,7 @@ data VTxContext = VTxContext
vtcVerifyAllIsKnown :: !Bool
-- , vtcSlotId :: !SlotId -- ^ Slot id of block transaction is checked in
-- , vtcLeaderId :: !StakeholderId -- ^ Leader id of block transaction is checked in
, vtcNetworkMagic :: !NetworkMagic
}

-- | Result of successful 'Tx' verification based on Utxo.
Expand Down Expand Up @@ -195,6 +196,11 @@ verifyOutputs VTxContext {..} (TxAux UnsafeTx {..} _) =
throwError $ ToilInvalidOutput i (TxOutUnknownAddressType addr)
when (isRedeemAddress addr) $
throwError $ ToilInvalidOutput i (TxOutRedeemAddressProhibited addr)
unless (addressHasValidMagic (attrData addrAttributes)) $
throwError $ ToilInvalidOutput i (TxOutAddressBadNetworkMagic addr)

addressHasValidMagic :: AddrAttributes -> Bool
addressHasValidMagic addrAttrs = vtcNetworkMagic == (aaNetworkMagic addrAttrs)

-- Verify inputs of a transaction after they have been resolved
-- (implies that they are known).
Expand Down
6 changes: 5 additions & 1 deletion chain/test/Test/Pos/Chain/Txp/Arbitrary.hs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import Pos.Core.Attributes (mkAttributes)
import Pos.Core.Common (Coin, IsBootstrapEraAddr (..),
makePubKeyAddress)
import Pos.Core.Merkle (MerkleNode (..), MerkleRoot (..))
import Pos.Core.NetworkMagic (NetworkMagic (..))
import Pos.Crypto (Hash, ProtocolMagic, SecretKey, SignTag (SignTx),
hash, sign, toPublic)

Expand Down Expand Up @@ -154,7 +155,7 @@ buildProperTx pm inputList (inCoin, outCoin) =
mkWitness fromSk =
PkWitness (toPublic fromSk) (sign pm SignTx fromSk $ TxSigData newTxHash)
makeTxOutput s c =
TxOut (makePubKeyAddress (IsBootstrapEraAddr True) $ toPublic s) c
TxOut (makePubKeyAddress fixedNM (IsBootstrapEraAddr True) $ toPublic s) c

-- | Well-formed transaction 'Tx'.
--
Expand Down Expand Up @@ -240,3 +241,6 @@ genTxPayload pm = mkTxPayload <$> genTxOutDist pm
instance Arbitrary TxPayload where
arbitrary = genTxPayload dummyProtocolMagic
shrink = genericShrink

fixedNM :: NetworkMagic
fixedNM = NetworkMainOrStage
6 changes: 5 additions & 1 deletion chain/test/Test/Pos/Chain/Txp/Example.hs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import Pos.Core.Attributes (mkAttributes)
import Pos.Core.Common (Coin (..), IsBootstrapEraAddr (..),
makePubKeyAddress)
import Pos.Core.Merkle (mkMerkleTree, mtRoot)
import Pos.Core.NetworkMagic (NetworkMagic (..))
import Pos.Crypto (AbstractHash (..), Hash, PublicKey (..),
RedeemSignature, SignTag (..), hash,
redeemDeterministicKeyGen, redeemSign, sign)
Expand All @@ -57,7 +58,7 @@ exampleTxInUtxo :: TxIn
exampleTxInUtxo = TxInUtxo exampleHashTx 47 -- TODO: loop here

exampleTxOut :: TxOut
exampleTxOut = TxOut (makePubKeyAddress (IsBootstrapEraAddr True) pkey) (Coin 47)
exampleTxOut = TxOut (makePubKeyAddress fixedNM (IsBootstrapEraAddr True) pkey) (Coin 47)
where
Right pkey = PublicKey <$> CC.xpub (getBytes 0 64)

Expand Down Expand Up @@ -92,3 +93,6 @@ exampleRedeemSignature = redeemSign exampleProtocolMagic SignForTestingOnly rsk

exampleHashTx :: Hash Tx
exampleHashTx = coerce (hash "golden" :: Hash Text)

fixedNM :: NetworkMagic
fixedNM = NetworkMainOrStage
Loading