Skip to content

Commit

Permalink
Merge pull request #333 from LATOKEN/secured-balance-update
Browse files Browse the repository at this point in the history
Secured balance update
  • Loading branch information
tbssajal authored Jan 13, 2023
2 parents 8a54bbc + e6b96cb commit c6d2d6e
Show file tree
Hide file tree
Showing 29 changed files with 1,348 additions and 135 deletions.
24 changes: 16 additions & 8 deletions src/Lachain.Benchmark/BlockchainBenchmark.cs
Original file line number Diff line number Diff line change
Expand Up @@ -295,8 +295,10 @@ private void _Bench_Emulate_Block(
const int txPerBlock = 1000;

Logger.LogInformation($"Setting initial balance for the 'From' address");
_stateManager.LastApprovedSnapshot.Balances.AddBalance(keyPair.PublicKey.GetAddress(),
Money.Parse("200000"));
_stateManager.LastApprovedSnapshot.Balances.MintLaToken(
keyPair.PublicKey.GetAddress(),
Money.Parse("200000")
);

var txReceipts = new List<TransactionReceipt>();

Expand Down Expand Up @@ -352,8 +354,10 @@ private void _Bench_Emulate_Execute_Tx(
const int txPerBlock = 1000;

Logger.LogInformation($"Setting initial balance for the 'From' address");
_stateManager.LastApprovedSnapshot.Balances.AddBalance(keyPair.PublicKey.GetAddress(),
Money.Parse("200000"));
_stateManager.LastApprovedSnapshot.Balances.MintLaToken(
keyPair.PublicKey.GetAddress(),
Money.Parse("200000")
);

var txReceipts = new List<TransactionReceipt>();

Expand Down Expand Up @@ -414,8 +418,10 @@ private void _Bench_Tx_Pool(
const int txPerBlock = 1000;

Logger.LogInformation($"Setting initial balance for the 'From' address");
_stateManager.LastApprovedSnapshot.Balances.AddBalance(keyPair.PublicKey.GetAddress(),
Money.Parse("200000"));
_stateManager.LastApprovedSnapshot.Balances.MintLaToken(
keyPair.PublicKey.GetAddress(),
Money.Parse("200000")
);

var txReceipts = new List<TransactionReceipt>();
for (int i = 0; i < txGenerate; i++)
Expand Down Expand Up @@ -463,8 +469,10 @@ private void _Bench_Execute_Blocks(
const int txPerBlock = 10;

Logger.LogInformation($"Setting initial balance for the 'From' address");
_stateManager.LastApprovedSnapshot.Balances.AddBalance(keyPair.PublicKey.GetAddress(),
Money.Parse("2000000"));
_stateManager.LastApprovedSnapshot.Balances.MintLaToken(
keyPair.PublicKey.GetAddress(),
Money.Parse("2000000")
);

for (var k = 0; k < txGenerate / txPerBlock; k++)
{
Expand Down
1 change: 1 addition & 0 deletions src/Lachain.Core/Blockchain/Hardfork/HardforkConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,6 @@ public class HardforkConfig
[JsonProperty("hardfork_12")] public ulong? Hardfork_12 { get; set; }
[JsonProperty("hardfork_13")] public ulong? Hardfork_13 { get; set; }
[JsonProperty("hardfork_14")] public ulong? Hardfork_14 { get; set; }
[JsonProperty("hardfork_15")] public ulong? Hardfork_15 { get; set; }
}
}
10 changes: 10 additions & 0 deletions src/Lachain.Core/Blockchain/Hardfork/HardforkHeights.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ public static class HardforkHeights
private static ulong Hardfork_12;
private static ulong Hardfork_13;
private static ulong Hardfork_14;
private static ulong Hardfork_15;

//we need this value as default deploy height
public static ulong GetHardfork_3()
Expand Down Expand Up @@ -96,6 +97,11 @@ public static bool IsHardfork_14Active(ulong height)
{
return height >= Hardfork_14;
}

public static bool IsHardfork_15Active(ulong height)
{
return height >= Hardfork_15;
}

public static void SetHardforkHeights(HardforkConfig hardforkConfig)
{
Expand Down Expand Up @@ -159,6 +165,10 @@ public static void SetHardforkHeights(HardforkConfig hardforkConfig)
if(hardforkConfig.Hardfork_14 is null)
throw new Exception("hardfork_14 is null");
Hardfork_14 = (ulong) hardforkConfig.Hardfork_14;

if(hardforkConfig.Hardfork_15 is null)
throw new Exception("hardfork_15 is null");
Hardfork_15 = (ulong) hardforkConfig.Hardfork_15;
}
}
}
8 changes: 5 additions & 3 deletions src/Lachain.Core/Blockchain/Operations/BlockManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -622,8 +622,10 @@ private OperatingError _TakeTransactionFee(
return OperatingError.InsufficientBalance;
}

return !snapshot.Balances.TransferBalance(transaction.Transaction.From,
ContractRegisterer.GovernanceContract, fee)
return !snapshot.Balances.TransferBalance(
transaction.Transaction.From, ContractRegisterer.GovernanceContract, fee, transaction,
HardforkHeights.IsHardfork_15Active(transaction.Block), HardforkHeights.IsHardfork_9Active(transaction.Block)
)
? OperatingError.InsufficientBalance
: OperatingError.Ok;
}
Expand Down Expand Up @@ -839,7 +841,7 @@ public bool TryBuildGenesisBlock()

// add balance to staking contract
var stakeAmount = Money.Parse(validator.StakeAmount);
snapshot.Balances.AddBalance(ContractRegisterer.StakingContract, stakeAmount, true);
snapshot.Balances.MintLaToken(ContractRegisterer.StakingContract, stakeAmount);
// set stake value
_userToStake.SetValue(validatorAddress, stakeAmount.ToUInt256().ToBytes());
// update stakers list
Expand Down
8 changes: 6 additions & 2 deletions src/Lachain.Core/Blockchain/Operations/TransactionExecuter.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Linq;
using Lachain.Core.Blockchain.Error;
using Lachain.Core.Blockchain.Hardfork;
using Lachain.Core.Blockchain.Interface;
using Lachain.Core.Blockchain.SystemContracts.ContractManager;
using Lachain.Core.Blockchain.VM;
Expand Down Expand Up @@ -56,7 +57,7 @@ public OperatingError Execute(Block block, TransactionReceipt receipt, IBlockcha
{
if (!receipt.Transaction.From.Equals(UInt160Utils.Zero)) return OperatingError.InvalidTransaction;
if (!receipt.Transaction.Invocation.IsEmpty) return OperatingError.InvalidTransaction;
snapshot.Balances.AddBalance(receipt.Transaction.To, transaction.Value.ToMoney(), true);
snapshot.Balances.MintLaToken(receipt.Transaction.To, transaction.Value.ToMoney());
return OperatingError.Ok;
}

Expand Down Expand Up @@ -85,7 +86,10 @@ public OperatingError Execute(Block block, TransactionReceipt receipt, IBlockcha

/* try to transfer funds from sender to recipient */
if (new Money(transaction.Value) > Money.Zero)
if (!snapshot.Balances.TransferBalance(transaction.From, transaction.To, new Money(transaction.Value)))
if (!snapshot.Balances.TransferBalance(
transaction.From, transaction.To, new Money(transaction.Value), receipt,
HardforkHeights.IsHardfork_15Active(receipt.Block), HardforkHeights.IsHardfork_9Active(receipt.Block)
))
return OperatingError.InsufficientBalance;
/* invoke required function or fallback */
return _InvokeContract(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@ private readonly ConcurrentDictionary<UInt160, Type> _contracts
private readonly IDictionary<UInt160, Dictionary<uint, (string methodName, MethodInfo methodInfo)>> _signatures
= new Dictionary<UInt160, Dictionary<uint, (string methodName, MethodInfo methodInfo)>>();

public static readonly UInt160 DeployContract = new BigInteger(0).ToUInt160();
public static readonly UInt160 LatokenContract = new BigInteger(1).ToUInt160();
public static readonly UInt160 GovernanceContract = new BigInteger(2).ToUInt160();
public static readonly UInt160 StakingContract = new BigInteger(3).ToUInt160();
public static readonly UInt160 NativeTokenContract = new BigInteger(4).ToUInt160();
public static UInt160 DeployContract => SystemContractAddresses.DeployContract;
public static UInt160 LatokenContract => SystemContractAddresses.LatokenContract;
public static UInt160 GovernanceContract => SystemContractAddresses.GovernanceContract;
public static UInt160 StakingContract => SystemContractAddresses.StakingContract;
public static UInt160 NativeTokenContract => SystemContractAddresses.NativeTokenContract;

public ContractRegisterer()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,14 +159,12 @@ public ExecutionStatus DistributeCycleRewardsAndPenalties(UInt256 cycle, SystemC

if (txFeesAmount > Money.Zero)
{
_context.Snapshot.Balances.SubBalance(
ContractRegisterer.GovernanceContract, txFeesAmount
);
_context.Snapshot.Balances.RemoveCollectedFees(txFeesAmount, _context.Receipt);
}

var totalReward = GetBlockReward().ToMoney() * (int) StakingContract.CycleDuration + txFeesAmount;
_context.Sender = ContractRegisterer.GovernanceContract;
var staking = new StakingContract(_context);
var nextContext = _context.NextContext(ContractRegisterer.GovernanceContract);
var staking = new StakingContract(nextContext);
staking.DistributeRewardsAndPenalties(totalReward.ToUInt256(), frame);
Emit(GovernanceInterface.EventDistributeCycleRewardsAndPenalties, totalReward.ToUInt256());
return ExecutionStatus.Ok;
Expand Down
54 changes: 47 additions & 7 deletions src/Lachain.Core/Blockchain/SystemContracts/NativeTokenContract.cs
Original file line number Diff line number Diff line change
Expand Up @@ -120,11 +120,50 @@ public ExecutionStatus Transfer(UInt160 recipient, UInt256 value, SystemContract
{
frame.UseGas(GasMetering.NativeTokenTransferCost);
var from = _context.Sender ?? throw new InvalidOperationException();
var result = _context.Snapshot.Balances.TransferBalance(
from,
recipient,
value.ToMoney()
);
bool result;
if (HardforkHeights.IsHardfork_15Active(_context.Receipt.Block))
{
var contract = _context.Snapshot.Contracts.GetContractByHash(from);
var isSystemContract = SystemContractAddresses.IsSystemContract(from);
if ((contract is null) && !isSystemContract)
{
// balance transfer from plain address
result = _context.Snapshot.Balances.TransferBalance(
from,
recipient,
value.ToMoney(),
_context.Receipt,
HardforkHeights.IsHardfork_15Active(_context.Receipt.Block),
HardforkHeights.IsHardfork_9Active(_context.Receipt.Block)
);
}
else if (isSystemContract)
{
// balance transfer from system contract address
// system contract balance transfer can happen here because the sender is the sender of the current context
// which means it is not possible to overwrite the sender address or pass via input data of transaction
result = _context.Snapshot.Balances.TransferSystemContractBalance(
from, recipient, value.ToMoney(), _context.Receipt,
HardforkHeights.IsHardfork_15Active(_context.Receipt.Block)
);
}
else
{
// balance transfer from contract address
result = _context.Snapshot.Balances.TransferContractBalance(from, recipient, value.ToMoney());
}
}
else
{
result = _context.Snapshot.Balances.TransferBalance(
from,
recipient,
value.ToMoney(),
_context.Receipt,
HardforkHeights.IsHardfork_15Active(_context.Receipt.Block),
HardforkHeights.IsHardfork_9Active(_context.Receipt.Block)
);
}
Emit(Lrc20Interface.EventTransfer, from, recipient, value);
frame.ReturnValue = ContractEncoder.Encode(null, (result ? 1 : 0).ToUInt256());
if (HardforkHeights.IsHardfork_13Active(frame.InvocationContext.Snapshot.Blocks.GetTotalBlockHeight()))
Expand All @@ -138,9 +177,10 @@ public ExecutionStatus TransferFrom(
)
{
frame.UseGas(GasMetering.NativeTokenTransferFromCost);
var allowance = GetAllowance(from, Sender()).ToMoney();
if (!SubAllowance(from, Sender(), value, frame))
return ExecutionStatus.ExecutionHalted;
var result = _context.Snapshot.Balances.TransferBalance(from, recipient, value.ToMoney());
var result = _context.Snapshot.Balances.TransferAllowance(from, recipient, value.ToMoney(), allowance);
Emit(Lrc20Interface.EventTransfer, from, recipient, value);
frame.ReturnValue = ContractEncoder.Encode(null, (result ? 1 : 0).ToUInt256());
if (HardforkHeights.IsHardfork_13Active(frame.InvocationContext.Snapshot.Blocks.GetTotalBlockHeight()))
Expand Down Expand Up @@ -200,7 +240,7 @@ public ExecutionStatus Mint(UInt160 address, UInt256 amount, SystemContractExecu
totalSupply + amountMoney > _context.Snapshot.Balances.GetAllowedSupply())
return ExecutionStatus.ExecutionHalted;

var newBalance = _context.Snapshot?.Balances.AddBalance(address, amountMoney, true);
var newBalance = _context.Snapshot?.Balances.MintLaToken(address, amountMoney);
if (newBalance is null)
return ExecutionStatus.ExecutionHalted;
Emit(Lrc20Interface.EventMinted, address, amount);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -704,8 +704,8 @@ public ExecutionStatus DistributeRewardsAndPenalties(UInt256 totalReward, System
var rewardToMint = SubPenalty(validatorAddress, validatorReward);
if (rewardToMint > Money.Zero)
{
var newBalance = _context.Snapshot.Balances.AddBalance(
validatorAddress, rewardToMint, true
var newBalance = _context.Snapshot.Balances.MintLaToken(
validatorAddress, rewardToMint
);
Logger.LogDebug($"Minted reward: {rewardToMint} LA for {validatorAddress.ToHex()}");
Logger.LogDebug($"New balance: {newBalance} LA of {validatorAddress.ToHex()}");
Expand Down
Loading

0 comments on commit c6d2d6e

Please sign in to comment.