Skip to content

Commit

Permalink
Merge pull request #870 from fassadlr/merge1200
Browse files Browse the repository at this point in the history
Merge release/1.2.0.0 to Master
  • Loading branch information
fassadlr authored Feb 3, 2022
2 parents bf69e03 + 5dee9b4 commit dd50793
Show file tree
Hide file tree
Showing 286 changed files with 3,230 additions and 6,666 deletions.
3 changes: 2 additions & 1 deletion Scripts/STRAXSidechainRegistrationScript.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,8 @@ While ( ( Get-MaxHeight ) -eq $null )
While ( ( Get-MaxHeight ) -gt ( Get-LocalIndexerHeight ) )
{
$a = Get-MaxHeight
$b = Get-LocalIndexerHeight
$b = Get-LocalIndexerHeight
$c = $a - $b
[int]$percentage = $b / $a * 100
""
Write-Host (Get-TimeStamp) "$percentage% Synced" -ForegroundColor Cyan
Expand Down
2 changes: 1 addition & 1 deletion src/FederationSetup/FederationSetup.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<Version>1.1.1.1</Version>
<Version>1.2.0.0</Version>
<Authors>Stratis Group Ltd.</Authors>
</PropertyGroup>

Expand Down
2 changes: 1 addition & 1 deletion src/FodyNlogAdapter/FodyNlogAdapter.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<AssemblyName>FodyNlogAdapter</AssemblyName>
<Version>1.1.1.1</Version>
<Version>1.2.0.0</Version>
<GeneratePackageOnBuild>False</GeneratePackageOnBuild>
<Authors>Stratis Group Ltd.</Authors>
<PackageId>Stratis.Utils.FodyNlogAdapter</PackageId>
Expand Down
8 changes: 4 additions & 4 deletions src/NBitcoin/BIP39/Mnemonic.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public Mnemonic(string mnemonic, Wordlist wordlist = null)
wordlist = Wordlist.AutoDetect(mnemonic) ?? Wordlist.English;

string[] words = mnemonic.Split((char[])null, StringSplitOptions.RemoveEmptyEntries);
_Mnemonic = string.Join(wordlist.Space.ToString(), words);
this._Mnemonic = string.Join(wordlist.Space.ToString(), words);

//if the sentence is not at least 12 characters or cleanly divisible by 3, it is bad!
if (!CorrectWordCount(words.Length))
Expand All @@ -54,7 +54,7 @@ public Mnemonic(Wordlist wordList, byte[] entropy = null)

int i = Array.IndexOf(entArray, entropy.Length * 8);
if(i == -1)
throw new ArgumentException("The length for entropy should be : " + String.Join(",", entArray), "entropy");
throw new ArgumentException("The length for entropy should be : " + string.Join(",", entArray), "entropy");

int cs = csArray[i];
byte[] checksum = Hashes.SHA256(entropy);
Expand Down Expand Up @@ -200,10 +200,10 @@ public ExtKey DeriveExtKey(string passphrase = null)
return new ExtKey(DeriveSeed(passphrase));
}

private static Byte[] Concat(Byte[] source1, Byte[] source2)
private static byte[] Concat(byte[] source1, byte[] source2)
{
//Most efficient way to merge two arrays this according to http://stackoverflow.com/questions/415291/best-way-to-combine-two-or-more-byte-arrays-in-c-sharp
var buffer = new Byte[source1.Length + source2.Length];
var buffer = new byte[source1.Length + source2.Length];
Buffer.BlockCopy(source1, 0, buffer, 0, source1.Length);
Buffer.BlockCopy(source2, 0, buffer, source1.Length, source2.Length);

Expand Down
2 changes: 1 addition & 1 deletion src/NBitcoin/ConsensusOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public class ConsensusOptions
/// </summary>
public const int SerializeTransactionNoWitness = 0x40000000;

/// <summary>Maximum size for a block in bytes. </summary>
/// <summary>Maximum size for a block in bytes.</summary>
public uint MaxBlockBaseSize { get; set; }

/// <summary>The maximum allowed weight for a block, see BIP 141 (network rule)</summary>
Expand Down
2 changes: 1 addition & 1 deletion src/NBitcoin/Money.cs
Original file line number Diff line number Diff line change
Expand Up @@ -857,7 +857,7 @@ public string Format(string format, object arg, IFormatProvider formatProvider)
i++;
}
char unit = format[i];
var unitToUseInCalc = MoneyUnit.BTC;
MoneyUnit unitToUseInCalc = MoneyUnit.BTC;
switch (unit)
{
case 'B':
Expand Down
4 changes: 2 additions & 2 deletions src/NBitcoin/NBitcoin.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@

<PropertyGroup>
<Company>NStratis</Company>
<Copyright>Copyright © Stratis Platform SA 2020</Copyright>
<Copyright>Copyright © Stratis Platform SA 2022</Copyright>
<Description>The C# Bitcoin Library based on NBitcoin</Description>
</PropertyGroup>

<PropertyGroup>
<Version>4.0.0.83</Version>
<Version>4.0.0.84</Version>
</PropertyGroup>

<PropertyGroup>
Expand Down
2 changes: 1 addition & 1 deletion src/NBitcoin/TransactionBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1584,7 +1584,7 @@ public int EstimateSize(Transaction tx, bool virtualSize)
int witSize = 0;
if (tx.HasWitness)
witSize += 2;
foreach (var txin in tx.Inputs.AsIndexedInputs())
foreach (IndexedTxIn txin in tx.Inputs.AsIndexedInputs())
{
ICoin coin = FindSignableCoin(txin) ?? FindCoin(txin.PrevOut);
if (coin == null)
Expand Down
2 changes: 1 addition & 1 deletion src/Stratis.Bitcoin.Api.Tests/ApiSettingsTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ public void GivenUseHttps_ThenUsesTheCorrectProtocol(bool useHttps, string expec
var nodeSettings = new NodeSettings(KnownNetworks.TestNet, args: new[] { $"-usehttps={useHttps}", "-certificatefilepath=nonNullValue" });

// Act.
var settings = FullNodeSetup(nodeSettings);
ApiSettings settings = FullNodeSetup(nodeSettings);

// Assert.
settings.UseHttps.Should().Be(useHttps);
Expand Down
2 changes: 1 addition & 1 deletion src/Stratis.Bitcoin.Cli/Stratis.Bitcoin.Cli.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<Version>1.1.1.1</Version>
<Version>1.2.0.0</Version>
<Authors>Stratis Group Ltd.</Authors>
<Company>Stratis Group Ltd.</Company>
<Product />
Expand Down
38 changes: 20 additions & 18 deletions src/Stratis.Bitcoin.Features.Api/NodeController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NBitcoin;
using NLog;
using NLog.Config;
using NLog.Targets;
using NLog.Targets.Wrappers;
using Stratis.Bitcoin.AsyncWork;
using Stratis.Bitcoin.Base;
using Stratis.Bitcoin.Builder.Feature;
using Stratis.Bitcoin.Configuration;
using Stratis.Bitcoin.Configuration.Logging;
using Stratis.Bitcoin.Connection;
using Stratis.Bitcoin.Consensus;
using Stratis.Bitcoin.Controllers.Models;
Expand All @@ -27,7 +27,6 @@
using Stratis.Bitcoin.Utilities;
using Stratis.Bitcoin.Utilities.JsonErrors;
using Stratis.Bitcoin.Utilities.ModelStateErrors;
using ILogger = Microsoft.Extensions.Logging.ILogger;
using LogLevel = NLog.LogLevel;
using Target = NBitcoin.Target;

Expand Down Expand Up @@ -221,33 +220,34 @@ public IActionResult Status([FromQuery] bool publish)
/// <param name="hash">The hash of the block to retrieve.</param>
/// <param name="isJsonFormat">A flag that specifies whether to return the block header in the JSON format. Defaults to true. A value of false is currently not supported.</param>
/// <returns>Json formatted <see cref="BlockHeaderModel"/>. <c>null</c> if block not found. Returns <see cref="Microsoft.AspNetCore.Mvc.IActionResult"/> formatted error if fails.</returns>
/// <exception cref="NotImplementedException">Thrown if isJsonFormat = false</exception>"
/// <exception cref="ArgumentException">Thrown if hash is empty.</exception>
/// <exception cref="ArgumentNullException">Thrown if logger is not provided.</exception>
/// <response code="200">Returns the blockheader if found.</response>
/// <response code="400">Null hash provided, BlockHeader does not exist or if isJsonFormat = false>/response>
/// <remarks>Binary serialization is not supported with this method.</remarks>
[Route("getblockheader")]
[HttpGet]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
[ProducesResponseType((int)HttpStatusCode.NotFound)]
public IActionResult GetBlockHeader([FromQuery] string hash, bool isJsonFormat = true)
{
try
{
Guard.NotEmpty(hash, nameof(hash));
if (string.IsNullOrEmpty(hash))
return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "Error", "Null hash provided.");

this.logger.LogDebug("GetBlockHeader {0}", hash);

if (!isJsonFormat)
{
this.logger.LogError("Binary serialization is not supported.");
throw new NotImplementedException();
return ErrorHelpers.BuildErrorResponse(HttpStatusCode.BadRequest, "Error", "Binary serialization is not supported.");
}

BlockHeaderModel model = null;
BlockHeader blockHeader = this.chainIndexer?.GetHeader(uint256.Parse(hash))?.Header;
if (blockHeader != null)
{
model = new BlockHeaderModel(blockHeader);
}
if (blockHeader == null)
return this.NotFound($"Block header for '{hash}' not found");

return this.Json(model);
return this.Json(new BlockHeaderModel(blockHeader));
}
catch (Exception e)
{
Expand Down Expand Up @@ -385,7 +385,7 @@ public IActionResult ValidateAddress([FromQuery] string address)

if (result.IsValid)
{
var scriptPubKey = BitcoinAddress.Create(address, this.network).ScriptPubKey;
NBitcoin.Script scriptPubKey = BitcoinAddress.Create(address, this.network).ScriptPubKey;
result.ScriptPubKey = scriptPubKey.ToHex();
result.IsWitness = scriptPubKey.IsWitness(this.network);
}
Expand Down Expand Up @@ -453,7 +453,7 @@ public async Task<IActionResult> GetTxOutAsync([FromQuery] string trxid, uint vo
/// <returns>The hex-encoded merkle proof.</returns>
[Route("gettxoutproof")]
[HttpGet]
public async Task<IActionResult> GetTxOutProofAsync([FromQuery] string[] txids, string blockhash = "")
public Task<IActionResult> GetTxOutProofAsync([FromQuery] string[] txids, string blockhash = "")
{
List<uint256> transactionIds = txids.Select(txString => uint256.Parse(txString)).ToList();

Expand Down Expand Up @@ -500,7 +500,7 @@ public async Task<IActionResult> GetTxOutProofAsync([FromQuery] string[] txids,

var result = new MerkleBlock(block.Block, transactionIds.ToArray());

return this.Json(result);
return Task.FromResult<IActionResult>(this.Json(result));
}

/// <summary>
Expand Down Expand Up @@ -529,6 +529,8 @@ public IActionResult Shutdown([FromBody] bool corsProtection = true)
/// Signals the node to rewind to the specified height.
/// This will be done via writing a flag to the .conf file so that on startup it be executed.
/// </summary>
/// <param name="height">The rewind height.</param>
/// <returns>A json text result indicating success or an <see cref="ErrorResult"/> indicating failure.</returns>
[Route("rewind")]
[HttpPut]
[ProducesResponseType((int)HttpStatusCode.OK)]
Expand Down Expand Up @@ -697,7 +699,7 @@ public IActionResult GetAsyncLoops()
/// <summary>
/// Schedules data folder storing chain state in the <see cref="DataFolder"/> for deletion on the next graceful shutdown.
/// </summary>
/// <returns></returns>
/// <returns>Returns an <see cref="OkResult"/>.</returns>
[HttpDelete]
[Route("datafolder/chain")]
public IActionResult DeleteChain()
Expand All @@ -717,7 +719,7 @@ public IActionResult DeleteChain()
/// <exception cref="ArgumentNullException">Thrown if fullnode is not provided.</exception>
internal ChainedHeader GetTransactionBlock(uint256 trxid, ChainIndexer chain)
{
Guard.NotNull(fullNode, nameof(fullNode));
Guard.NotNull(this.fullNode, nameof(this.fullNode));

ChainedHeader block = null;
uint256 blockid = this.blockStore?.GetBlockIdByTransactionId(trxid);
Expand Down
3 changes: 2 additions & 1 deletion src/Stratis.Bitcoin.Features.Api/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json.Converters;
using Swashbuckle.AspNetCore.SwaggerGen;
using Swashbuckle.AspNetCore.SwaggerUI;

Expand Down Expand Up @@ -74,7 +73,9 @@ public void ConfigureServices(IServiceCollection services)
{
options.Filters.Add(typeof(LoggingActionFilter));
#pragma warning disable ASP0000 // Do not call 'IServiceCollection.BuildServiceProvider' in 'ConfigureServices'
ServiceProvider serviceProvider = services.BuildServiceProvider();
#pragma warning restore ASP0000 // Do not call 'IServiceCollection.BuildServiceProvider' in 'ConfigureServices'
var apiSettings = (ApiSettings)serviceProvider.GetRequiredService(typeof(ApiSettings));
if (apiSettings.KeepaliveTimer != null)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<AssemblyName>Stratis.Bitcoin.Features.Api</AssemblyName>
<OutputType>Library</OutputType>
<PackageId>Stratis.Features.Api</PackageId>
<Version>1.1.1.1</Version>
<Version>1.2.0.0</Version>
<GeneratePackageOnBuild>False</GeneratePackageOnBuild>
<ApplicationIcon />
<OutputTypeEx>library</OutputTypeEx>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
using System.Runtime.InteropServices;
using LiteDB;
using NBitcoin;
using Stratis.Bitcoin.Configuration.Logging;
using Stratis.Bitcoin.Features.BlockStore.AddressIndexing;
using Xunit;

Expand All @@ -23,7 +22,7 @@ public AddressIndexerOutpointsRepositoryTests()
FileMode fileMode = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? FileMode.Exclusive : FileMode.Shared;
var db = new LiteDatabase(new ConnectionString() { Filename = this.RandomString(20) + ".litedb", Mode = fileMode });

this.repository = new AddressIndexerOutpointsRepository(db, new ExtendedLoggerFactory(), this.maxItems);
this.repository = new AddressIndexerOutpointsRepository(db, this.maxItems);
}

[Fact]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
using NBitcoin;
using Stratis.Bitcoin.AsyncWork;
using Stratis.Bitcoin.Configuration;
using Stratis.Bitcoin.Configuration.Logging;
using Stratis.Bitcoin.Consensus;
using Stratis.Bitcoin.Controllers.Models;
using Stratis.Bitcoin.Features.BlockStore.AddressIndexing;
Expand Down Expand Up @@ -52,7 +51,7 @@ public AddressIndexerTests()

var utxoIndexerMock = new Mock<IUtxoIndexer>();

this.addressIndexer = new AddressIndexer(storeSettings, dataFolder, new ExtendedLoggerFactory(), this.network, stats.Object,
this.addressIndexer = new AddressIndexer(storeSettings, dataFolder, this.network, stats.Object,
this.consensusManagerMock.Object, this.asyncProviderMock.Object, indexer, new DateTimeProvider(), utxoIndexerMock.Object);

this.genesisHeader = new ChainedHeader(this.network.GetGenesis().Header, this.network.GetGenesis().Header.GetHash(), 0);
Expand Down Expand Up @@ -182,7 +181,7 @@ public void OutPointCacheCanRetrieveExisting()
FileMode fileMode = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? FileMode.Exclusive : FileMode.Shared;

var database = new LiteDatabase(new ConnectionString() { Filename = dbPath, Mode = fileMode });
var cache = new AddressIndexerOutpointsRepository(database, new ExtendedLoggerFactory());
var cache = new AddressIndexerOutpointsRepository(database);

var outPoint = new OutPoint(uint256.Parse("0000af9ab2c8660481328d0444cf167dfd31f24ca2dbba8e5e963a2434cffa93"), 0);

Expand All @@ -205,7 +204,7 @@ public void OutPointCacheCannotRetrieveNonexistent()
FileMode fileMode = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? FileMode.Exclusive : FileMode.Shared;

var database = new LiteDatabase(new ConnectionString() { Filename = dbPath, Mode = fileMode });
var cache = new AddressIndexerOutpointsRepository(database, new ExtendedLoggerFactory());
var cache = new AddressIndexerOutpointsRepository(database);

Assert.False(cache.TryGetOutPointData(new OutPoint(uint256.Parse("0000af9ab2c8660481328d0444cf167dfd31f24ca2dbba8e5e963a2434cffa93"), 1), out OutPointData retrieved));
Assert.Null(retrieved);
Expand All @@ -220,7 +219,7 @@ public void OutPointCacheEvicts()
FileMode fileMode = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? FileMode.Exclusive : FileMode.Shared;

var database = new LiteDatabase(new ConnectionString() { Filename = dbPath, Mode = fileMode });
var cache = new AddressIndexerOutpointsRepository(database, new ExtendedLoggerFactory(), 2);
var cache = new AddressIndexerOutpointsRepository(database, 2);

Assert.Equal(0, cache.Count);
Assert.Equal(0, database.GetCollection<OutPointData>(CollectionName).Count());
Expand Down Expand Up @@ -271,7 +270,7 @@ public void AddressCacheCanRetrieveExisting()
FileMode fileMode = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? FileMode.Exclusive : FileMode.Shared;

var database = new LiteDatabase(new ConnectionString() { Filename = dbPath, Mode = fileMode });
var cache = new AddressIndexRepository(database, new ExtendedLoggerFactory());
var cache = new AddressIndexRepository(database);

string address = "xyz";
var balanceChanges = new List<AddressBalanceChange>();
Expand Down Expand Up @@ -300,7 +299,7 @@ public void AddressCacheRetrievesBlankRecordForNonexistent()
FileMode fileMode = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? FileMode.Exclusive : FileMode.Shared;

var database = new LiteDatabase(new ConnectionString() { Filename = dbPath, Mode = fileMode });
var cache = new AddressIndexRepository(database, new ExtendedLoggerFactory());
var cache = new AddressIndexRepository(database);

AddressIndexerData retrieved = cache.GetOrCreateAddress("xyz");

Expand All @@ -319,7 +318,7 @@ public void AddressCacheEvicts()
FileMode fileMode = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? FileMode.Exclusive : FileMode.Shared;

var database = new LiteDatabase(new ConnectionString() { Filename = dbPath, Mode = fileMode });
var cache = new AddressIndexRepository(database, new ExtendedLoggerFactory(), 4);
var cache = new AddressIndexRepository(database, 4);

// Recall, each index entry counts as 1 and each balance change associated with it is an additional 1.
Assert.Equal(0, database.GetCollection<AddressIndexerData>(CollectionName).Count());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,9 @@ public void Get_Block_When_Hash_Is_Not_Found_Should_Return_OkResult_WithMessage(

IActionResult response = controller.GetBlock(new SearchByHashRequest() { Hash = new uint256(1).ToString(), OutputJson = true });

response.Should().BeOfType<OkObjectResult>();
var result = (OkObjectResult)response;
result.StatusCode.Should().Be((int)HttpStatusCode.OK);
response.Should().BeOfType<NotFoundObjectResult>();
var result = (NotFoundObjectResult)response;
result.StatusCode.Should().Be((int)HttpStatusCode.NotFound);
result.Value.Should().Be("Block not found");
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,7 @@ public async Task ReorgedBlocksAreNotSavedAsync()
/// <summary>
/// Tests reorgs inside the batch and inside the database at the same time.
/// </summary>
/// <returns>The asynchronous task.</returns>
[Fact]
[Trait("Unstable", "True")]
public async Task ReorgedBlocksAreDeletedFromRepositoryIfReorgDetectedAsync()
Expand Down
Loading

0 comments on commit dd50793

Please sign in to comment.