Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/*
Copyright (c) 2017 Paul Georgiou
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Threading;
using NBitcoin;
using NBitcoin.RPC;
using Newtonsoft.Json;
namespace SegwitStats
{
struct Datapoint
{
public int Height;
public int Size;
public int Weight;
public int OptimizedSize;
public int OptimizedWeight;
}
class Program
{
const string RpcCredentials = "user:pass";
const int TotalCount = 4032;
const int Period = 144;
private string fileName;
private Block ConvertToSegwit(Block block)
{
var push20bytes = Op.GetPushOp(Enumerable.Repeat((byte)0, 20).ToArray());
var push32bytes = Op.GetPushOp(Enumerable.Repeat((byte)0, 32).ToArray());
var result = block.Clone();
foreach (var tx in result.Transactions)
{
if (!tx.IsCoinBase)
{
foreach (var input in tx.Inputs)
{
if (input.WitScript.PushCount == 0)
{
input.WitScript = new WitScript(new Script(input.ScriptSig.ToOps()));
}
input.ScriptSig = Script.Empty;
}
}
foreach (var output in tx.Outputs)
{
var template = output.ScriptPubKey.FindTemplate();
if (template != null) switch (template.Type)
{
case TxOutType.TX_PUBKEYHASH:
output.ScriptPubKey = new Script(OpcodeType.OP_0, push20bytes);
break;
case TxOutType.TX_SCRIPTHASH:
output.ScriptPubKey = new Script(OpcodeType.OP_0, push32bytes);
break;
default:
break;
}
}
}
return result;
}
private Block RemoveWitnesses(Block block)
{
var result = block.Clone();
result.Transactions.ForEach(tx => tx.Inputs.ForEach(i => { i.WitScript = WitScript.Empty; }));
return result;
}
private int Weight(int size, int baseSize) => size + 3 * baseSize;
private void WriteToFile(Dictionary<int, Datapoint> stats)
{
var result = new Dictionary<string, List<int[]>>();
var data = stats.Values.ToList();
data.Sort(new Comparison<Datapoint>((l, r) => l.Height.CompareTo(r.Height)));
var output = data.Select(d => new int[] { d.Height, d.Size, d.Weight, d.OptimizedSize, d.OptimizedWeight }).ToList();
result.Add("last", new List<int[]>(Period));
for (int i = TotalCount - Period; i < TotalCount; i++)
{
result["last"].Add(output[i]);
}
result.Add("all", new List<int[]>(TotalCount / Period));
for (int i = 0; i < TotalCount; i += Period)
{
var sum = new int[] { output[i][0], 0, 0, 0, 0 };
for (int j = 0; j < Period; j++)
{
for (int k = 1; k < 5; k++)
{
sum[k] += output[i + j][k];
}
}
for (int k = 1; k < 5; k++)
{
sum[k] /= Period;
}
result["all"].Add(sum);
}
for (int i = 0; i < 10; i++)
{
try
{
File.WriteAllText(fileName, JsonConvert.SerializeObject(result));
break;
}
catch (Exception)
{
Thread.Sleep(100);
}
}
}
private void Run()
{
var rpc = new RPCClient(RPCCredentialString.Parse(RpcCredentials), Network.Main);
var blockStats = new Dictionary<int, Datapoint>();
int lastHeight = 0;
while (true)
{
try
{
int height = rpc.GetBlockCount();
if (height > lastHeight)
{
int count = height - lastHeight;
count = count > TotalCount ? TotalCount : count + 6;
Console.WriteLine("Computing {0} blocks...", count);
for (int i = 0; i < count; i++)
{
Console.Write("{0,5}", i);
int curHeight = height - i;
var block = rpc.GetBlock(curHeight);
int size, weight, osize, oweight;
size = block.GetSerializedSize();
weight = Weight(size, RemoveWitnesses(block).GetSerializedSize());
block = ConvertToSegwit(block);
osize = block.GetSerializedSize();
oweight = Weight(size, RemoveWitnesses(block).GetSerializedSize());
blockStats[curHeight] = new Datapoint() { Height = curHeight, Size = size, Weight = weight, OptimizedSize = osize, OptimizedWeight = oweight };
}
var keys = blockStats.Keys.ToArray();
foreach (int i in keys)
{
if (i > height || i <= height - TotalCount)
blockStats.Remove(i);
}
WriteToFile(blockStats);
lastHeight = height;
Console.WriteLine();
Console.WriteLine("...done.");
}
else
{
Thread.Sleep(1000);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
Thread.Sleep(1000);
}
}
}
static void Main(string[] args)
{
var p = new Program();
if (args.Length > 0)
p.fileName = args[0];
else
p.fileName = "stats.json";
p.Run();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.