private void InitTidalLib() { var initTidal = new Tidal(); TidalController = new TidalController(); TidalController.ApiRequest <CountryModel>("/country/"); TidalController.ApiRequest <LoginModel>($"/login/username?countryCode={TidalController.Tidal.CountryModel.CountryCode}", TidalController.RequestType.Post, $"username={Configuration.ConfigData.Login.TidalUserName}&password={Configuration.HashUtility.DecryptHash(Configuration.ConfigData.Login.TidalPassword)}"); TidalController.ApiRequest <UsersSubscriptionsModel>($"/users/{TidalController.Tidal.LoginModel.UserId}/subscription?sessionId={TidalController.Tidal.LoginModel.SessionId}&countryCode={TidalController.Tidal.CountryModel.CountryCode}"); TidalController.ApiRequest <FeaturedAlbumsModel>($"/featured/new/albums?limit=100&sessionId={TidalController.Tidal.LoginModel.SessionId}&countryCode={TidalController.Tidal.CountryModel.CountryCode}"); var featureAlbumsDataTabel = Configuration.ToDataTable(TidalController.Tidal.FeaturedAlbumsModel.Items); DataGridTopAlbums.ItemsSource = featureAlbumsDataTabel.AsDataView(); }
public int addTidalInfo(IEnumerable <TidalDeserialize> tidalInfoSource, int rowCount, string localName) { var count = rowCount; foreach (TidalDeserialize item in tidalInfoSource) { int timeCount = item.weatherElement[2].time.Count(); for (var j = 0; j <= timeCount - 1; j++) { var newTidal = new Tidal(); newTidal.tidalID = count; newTidal.locationName = localName; //農曆 newTidal.chineseDateTimeName = item.weatherElement[0].elementName; newTidal.chineseDateTime = item.weatherElement[0].elementValue; //潮差 newTidal.tidalDiffName = item.weatherElement[1].elementName; newTidal.tidalDiff = item.weatherElement[1].elementValue; newTidal.dataTime = item.weatherElement[2].time[j].dataTime; //潮汐 newTidal.tidalStatusName = item.weatherElement[2].time[j].parameter[0].parameterName; newTidal.tidalStatus = item.weatherElement[2].time[j].parameter[0].parameterValue; //潮高(TWVD) newTidal.tidalTWVDName = item.weatherElement[2].time[j].parameter[1].parameterName; newTidal.tidalTWVD = item.weatherElement[2].time[j].parameter[1].parameterValue + item.weatherElement[2].time[j].parameter[1].parameterMeasure; //潮高(當地) newTidal.tidalLocalName = item.weatherElement[2].time[j].parameter[2].parameterName; newTidal.tidalLocal = item.weatherElement[2].time[j].parameter[2].parameterValue + item.weatherElement[2].time[j].parameter[2].parameterMeasure; //潮高(相對海圖) newTidal.tidalRelationSeaName = item.weatherElement[2].time[j].parameter[3].parameterName; newTidal.tidalRelationSea = item.weatherElement[2].time[j].parameter[3].parameterValue + item.weatherElement[2].time[j].parameter[3].parameterMeasure; _db.Tidal.InsertOnSubmit(newTidal); count++; } } _db.SubmitChanges(); return(count); }
// Command methods and proccess public static void GetInput() { while (true) { bool argumentFound = false; string argument = Console.ReadLine(); if (argument == "getbcinfo") { PrintChainInfo(); argumentFound = true; } if (argument == "setsecure") { string s = argument.Replace("setsecure", ""); s = s.Replace(" ", ""); if (s == "1") { SECURE_MODE = true; Console.WriteLine("Secure mode set to true."); } if (s == "0") { SECURE_MODE = true; Console.WriteLine("Secure mode set to false."); } argumentFound = true; } if (argument.Contains("gettidal")) { uint unixTimestamp = (uint)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; Console.WriteLine("Water height from harmonics at St-Nazaire : " + Tidal.GetTidalAtSpecificTime(unixTimestamp) + "meters"); argumentFound = true; } if (argument == "getcominfo") { arduino.GetPortReady(); argumentFound = true; } if (argument.Contains("setarduino")) { string s = argument.Replace("setarduino", ""); s = s.Replace(" ", ""); arduino.Initialize(s); argumentFound = true; } if (argument.Contains("setseapow")) { string s = argument.Replace("setseapow", ""); s = s.Replace(" ", ""); uint val = 0; if (uint.TryParse(s, out val)) { if (ValidYesOrNo("[Warning] If you change SEA_FORCE parameters, you should do it on all the network nodes...")) { float old_val = SEA_FORCE; SEA_FORCE = val; Console.WriteLine("Sea force successfully changed from " + old_val + " to " + SEA_FORCE); } } else { Print("bad arguments "); } argumentFound = true; } if (argument.Contains("setport")) { string s = argument.Replace("setport", ""); s = s.Replace(" ", ""); int port = 37; if (int.TryParse(s, out port)) { ACTUAL_PORT = port; Console.WriteLine("new port for data request is " + ACTUAL_PORT); argumentFound = true; } else { Print("bad arguments "); } argumentFound = true; } if (argument.Contains("setbrcparam")) { string maxArgs = GetStringAfterArgs(argument, "max:"); string fbcArgs = GetStringAfterArgs(argument, "fbc:"); uint max = 0; uint fbc = 0; if (uint.TryParse(maxArgs, out max)) { BROADCAST_BLOCKS_LIMIT = max; Console.WriteLine("new broadcast blocks max limit : " + BROADCAST_BLOCKS_LIMIT); } if (uint.TryParse(fbcArgs, out fbc)) { BROADCAST_FULL_BLOCKCHAIN_CLOCK = fbc; Console.WriteLine("full blockchain will be broadcast every " + BROADCAST_FULL_BLOCKCHAIN_CLOCK + " minutes. "); } argumentFound = true; } if (argument == "netconnect") { uint unixTimestamp = (uint)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalMinutes; LATEST_FBROADCAST_TICK = unixTimestamp; NT = new network(); NT.Initialize(); argumentFound = true; } if (argument == "nettest 1") { if (NT != null) { NT.BroadcastFile(GetLatestBlockChainFilePath(), 1); } else { Console.WriteLine("You're offline. Please use netconnect to get online. "); } argumentFound = true; } if (argument.Contains("nettest 2")) { if (NT != null) { string s = argument.Replace("nettest 2", ""); s = s.Replace(" ", ""); string[] args = s.Split(':'); if (args.Length == 2) { uint start = 0; uint end = 0; if (uint.TryParse(args[0], out start) && uint.TryParse(args[1], out end)) { Console.WriteLine("sending from " + start + " to " + end); NT.BroadcastBlockchain(start, end); } } else { Console.WriteLine("wrong args"); } } else { Console.WriteLine("You're offline. Please use netconnect to get online. "); } argumentFound = true; } if (argument == "nettest 3") { if (NT != null) { NT.BroadcastFile(_folderPath + "ptx", 2); } else { Console.WriteLine("You're offline. Please use netconnect to get online. "); } argumentFound = true; } if (argument.Contains("readblockascii")) { string s = argument.Replace("readblockascii", ""); s = s.Replace(" ", ""); uint index = 0; bool success = uint.TryParse(s, out index); if (success) { Block b = GetBlockAtIndex(index); if (b == null) { Console.WriteLine("Block can't be found."); } else { Console.WriteLine("[ block data ]"); PrintBlockInASCII(b); } argumentFound = true; } else { Console.WriteLine("invalid argument"); } argumentFound = true; } if (argument.Contains("getblockinfo")) { string s = argument.Replace("getblockinfo", ""); s = s.Replace(" ", ""); uint index = 0; bool success = uint.TryParse(s, out index); if (success) { Block b = GetBlockAtIndex(index); if (b == null) { Console.WriteLine("Block can't be found."); } else { Console.WriteLine("[ block data ]"); PrintBlockData(b); } argumentFound = true; } else { Console.WriteLine("invalid argument"); } argumentFound = true; } if (argument == "createwallet") { GenerateNewPairKey(); argumentFound = true; } if (argument.Contains("getutxo")) { string s = argument.Replace("getutxo", ""); s = s.Replace(" ", ""); uint index = 0; bool success = uint.TryParse(s, out index); if (success) { UTXO utxo = GetOfficialUTXOAtPointer(index); if (utxo == null) { Console.WriteLine("UTXO of this public Key not existing in UTXO Set "); } else { Console.WriteLine("UTXO Hash :" + SHAToHex(utxo.HashKey, false)); Console.WriteLine("UTXO Sold :" + utxo.Sold); Console.WriteLine("UTXO Token :" + utxo.TokenOfUniqueness); } argumentFound = true; } } if (argument.Contains("getutxop")) { string path = argument.Replace("location", AppDomain.CurrentDomain.BaseDirectory.Remove(AppDomain.CurrentDomain.BaseDirectory.Length - 1)); path = getfilePath(path.ToCharArray()); if (path.Length == 0) { Console.WriteLine("invalid argument. Please set path of your public key file in quote. "); } else { Console.WriteLine(path); if (File.Exists(path)) { byte[] pkeyHASH = ComputeSHA256(File.ReadAllBytes(path)); Console.WriteLine("result for hash key : " + SHAToHex(pkeyHASH, false)); uint myUTXOP = GetUTXOPointer(pkeyHASH); UTXO myUTXO = GetOfficialUTXOAtPointer(myUTXOP); if (myUTXO != null) { Console.WriteLine("UTXO Hash :" + SHAToHex(pkeyHASH, false)); Console.WriteLine("UTXO Pointer :" + myUTXOP); Console.WriteLine("UTXO Sold :" + myUTXO.Sold); Console.WriteLine("UTXO Token :" + myUTXO.TokenOfUniqueness); } else { Console.WriteLine("UTXO of this public Key not existing in UTXO Set "); } } else { Console.WriteLine("Path : " + path + " does not exist. Please set path of your public key file. "); } argumentFound = true; } } if (argument == "verifychain") { if (ValidYesOrNo("[WARNING] Verify blockchain can take a lot of time.")) { Console.WriteLine("Verifying Blockchain..."); if (isBlockChainValid()) { Console.WriteLine("Blockchain is Valid! "); } else { Console.WriteLine("Blockchain is not valid! "); } } argumentFound = true; } if (argument == "buildutxos") { if (ValidYesOrNo("[WARNING] It will delete current UTXO Set, then rebuilt it can take a lot of time.")) { Console.WriteLine("Please wait during UTXO Set writting..."); BuildUTXOSet(); Console.WriteLine("UTXO Set writting finished!"); } argumentFound = true; } if (argument == "initchain") { if (ValidYesOrNo("[WARNING] It will delete UTXO Set, blockchain files, PTX file and forks. You will be disconnected! ")) { NT = null; // we should close nt ClearAllFiles(); CheckFilesAtRoot(); PrintChainInfo(); } argumentFound = true; } if (argument.Contains("mine")) { //mine pkey:[pkeypath] utxop:[utxop] minlock:[] ntime:[] // find pkey argumentFound = true; string pkeyArgs = GetStringAfterArgs(argument, "pkey:", '\"'); string utxopArgs = GetStringAfterArgs(argument, "utxop:"); string minlockArgs = GetStringAfterArgs(argument, "minlock:"); string ntimeArgs = GetStringAfterArgs(argument, "ntime:"); string path = ""; uint utxopointer = 0; if (pkeyArgs.Length != 0) { path = pkeyArgs.Replace("location", AppDomain.CurrentDomain.BaseDirectory.Remove(AppDomain.CurrentDomain.BaseDirectory.Length - 1)); path = getfilePath(path.ToCharArray()); } else { // automatically detect if there is a key in folder string[] files = Directory.GetFiles(_folderPath, "publicKey", SearchOption.AllDirectories); if (files.Length > 0) { if (files.Length > 1) { Console.WriteLine("Multiple public keys have been found! "); if (ValidYesOrNo("This will automatically use " + files[0] + "...")) { path = files[0]; } } else { Console.WriteLine("Will use key " + files[0]); path = files[0]; } } else { Console.WriteLine("No public key found in directories and subdirectories. Please set a path in argument."); } } if (File.Exists(path)) { byte[] pkeyHASH = ComputeSHA256(File.ReadAllBytes(path)); bool Continue = true; if (utxopArgs.Length == 0) { if (!ValidYesOrNo("[WARNING] You didn't set an UTXO pointer.")) { Continue = false; } } else { uint parsePointer = 0; if (!uint.TryParse(utxopArgs, out parsePointer) && Continue) { if (!ValidYesOrNo("[WARNING] Incorrect UTXO pointer") && Continue) { Continue = false; } } else { UTXO utxo = GetOfficialUTXOAtPointer(parsePointer); if (utxo == null && Continue) { if (!ValidYesOrNo("[WARNING] Incorrect UTXO pointer")) { Continue = false; } } else { if (!utxo.HashKey.SequenceEqual(pkeyHASH) && Continue) { if (!ValidYesOrNo("[WARNING] Incorrect UTXO pointer")) { Continue = false; } } } if (parsePointer == 0 && Continue) { if (!ValidYesOrNo("[WARNING] Incorrect UTXO pointer")) { Continue = false; } } utxopointer = parsePointer; } } if (Continue) { uint mnlock = 5000; uint nTime = 0; if (minlockArgs.Length != 0) { uint.TryParse(minlockArgs, out mnlock); } if (ntimeArgs.Length != 0) { uint.TryParse(ntimeArgs, out nTime); } MYMINERPKEY = pkeyHASH; MYUTXOPOINTER = utxopointer; MAXLOCKTIMESETTING = mnlock; NTIMES = nTime; MININGENABLED = true; argumentFound = true; } } else { Console.WriteLine("Path : " + path + " does not exist. Please set path of your public key file. "); } } if (argument.Contains("newtx")) { //newtx sprkey: spukey: sutxop: amount: rpukey: rutxop: fee: lock: ( offset in sec since now we want to create the tx) while (argument.Contains("location")) { argument = argument.Replace("location", AppDomain.CurrentDomain.BaseDirectory.Remove(AppDomain.CurrentDomain.BaseDirectory.Length - 1)); } //string path = pkeyArgs.Replace("location", AppDomain.CurrentDomain.BaseDirectory); //path = getfilePath(path.ToCharArray()); string sprkeyArgs = getfilePath(GetStringAfterArgs(argument, "sprkey:", '\"').ToCharArray()); //< i use get path string spukeyArgs = getfilePath(GetStringAfterArgs(argument, "spukey:", '\"').ToCharArray()); string sutxopArgs = GetStringAfterArgs(argument, "sutxop:"); //< string amountArgs = GetStringAfterArgs(argument, "amount:"); string rpukeyArgs = getfilePath(GetStringAfterArgs(argument, "rpukey:", '\"').ToCharArray()); string feeArgs = GetStringAfterArgs(argument, "fee:"); string locktimeArgs = GetStringAfterArgs(argument, "lock:"); if (sprkeyArgs.Length == 0 || spukeyArgs.Length == 0 || sutxopArgs.Length == 0 || amountArgs.Length == 0 || rpukeyArgs.Length == 0 || feeArgs.Length == 0 || locktimeArgs.Length == 0) { Console.WriteLine("missing argument. see getcmdinfo. "); } else { uint sutxop = 0; uint amount = 0; uint rutxop = 0; uint fee = 0; uint locktime = 0; if (!File.Exists(sprkeyArgs) || !File.Exists(spukeyArgs) || !uint.TryParse(sutxopArgs, out sutxop) || !uint.TryParse(amountArgs, out amount) || !File.Exists(rpukeyArgs) || !uint.TryParse(feeArgs, out fee) || !uint.TryParse(locktimeArgs, out locktime)) { Console.WriteLine("invalid argument. see getcmdinfo. "); } else { SetUpTx(sprkeyArgs, spukeyArgs, sutxop, amount, rpukeyArgs, rutxop, fee, locktime); argumentFound = true; } } } if (argument.Contains("hideapoeminatransaction")) { //newtx sprkey: spukey: sutxop: amount: rpukey: rutxop: fee: lock: while (argument.Contains("location")) { argument = argument.Replace("location", AppDomain.CurrentDomain.BaseDirectory.Remove(AppDomain.CurrentDomain.BaseDirectory.Length - 1)); } //string path = pkeyArgs.Replace("location", AppDomain.CurrentDomain.BaseDirectory); //path = getfilePath(path.ToCharArray()); string sprkeyArgs = getfilePath(GetStringAfterArgs(argument, "sprkey:", '\"').ToCharArray()); //< i use get path string spukeyArgs = getfilePath(GetStringAfterArgs(argument, "spukey:", '\"').ToCharArray()); string sutxopArgs = GetStringAfterArgs(argument, "sutxop:"); //< string poem = getfilePath(GetStringAfterArgs(argument, "poem:", '\"').ToCharArray()); //string rpukeyArgs = getfilePath(GetStringAfterArgs(argument, "rpukey:", '\"').ToCharArray()); // string rutxopArgs = GetStringAfterArgs(argument, "rutxop:"); string feeArgs = GetStringAfterArgs(argument, "fee:"); string locktimeArgs = GetStringAfterArgs(argument, "lock:"); if (sprkeyArgs.Length == 0 || spukeyArgs.Length == 0 || sutxopArgs.Length == 0 || feeArgs.Length == 0 || locktimeArgs.Length == 0 || poem.Length == 0) { Console.WriteLine("missing argument. see getcmdinfo. "); } else { uint sutxop = 0; uint rutxop = 0; uint fee = 0; uint locktime = 0; if (!File.Exists(sprkeyArgs) || !File.Exists(spukeyArgs) || !uint.TryParse(sutxopArgs, out sutxop) || !uint.TryParse(feeArgs, out fee) || !uint.TryParse(locktimeArgs, out locktime)) { Console.WriteLine("invalid argument. see getcmdinfo. "); } else { //SetUpTx(sprkeyArgs, spukeyArgs, sutxop, amount, rpukeyArgs, rutxop, fee, locktime); Console.WriteLine("poem is " + poem); XYPoem.BuildandHidePoemsInPublicKeyHash(sprkeyArgs, spukeyArgs, sutxop, 0, poem, rutxop, fee, locktime); argumentFound = true; } } } if (argument.Contains("reqtx")) { argument = argument.Replace("reqtx", ""); argument = argument.Replace("location", AppDomain.CurrentDomain.BaseDirectory.Remove(AppDomain.CurrentDomain.BaseDirectory.Length - 1)); // enlever le dernier / ici ! string txPath = getfilePath(argument.ToCharArray()); if (File.Exists(txPath)) { PendingPTXFiles.Add(new Tuple <bool, string>(true, txPath)); argumentFound = true; } else { Console.WriteLine("Path : " + txPath + " does not exist. Please set path of your public key file. "); } } if (!argumentFound) { Console.WriteLine("invalid input. type getcmdinfo for command information. "); } if (argument.Contains("getcmdinfo")) { PrintArgumentInfo(); } Console.WriteLine(""); } }
// Main methods for blocks validation public static void ProccessTempBlocks(string _filePath, bool needPropagate) // MAIN FUNCTION TO VALID BLOCK { Print("Proccess File block : " + _filePath); FileInfo f = new FileInfo(_filePath); if (f.Length < 8) { Console.WriteLine("[BLOCKS REFUSED] bad file length!"); File.Delete(_filePath); return; } if (!isHeaderCorrectInBlockFile(_filePath)) { Console.WriteLine("[BLOCKS REFUSED] header incorrect!"); File.Delete(_filePath); return; } uint firstTempIndex = BitConverter.ToUInt32(GetBytesFromFile(4, 8, _filePath), 0); uint latestTempIndex = BitConverter.ToUInt32(GetBytesFromFile(0, 4, _filePath), 0); Print(firstTempIndex + " " + latestTempIndex); uint latestOfficialIndex = RequestLatestBlockIndex(true); bool HardFork = false; Print(((int)(latestOfficialIndex - MAX_RETROGRADE)).ToString()); if ((int)firstTempIndex <= (int)(latestOfficialIndex - MAX_RETROGRADE)) // create a uint max value error ! { if (firstTempIndex == 0) { Console.WriteLine("[BLOCKS REFUSED] no genesis allowed!"); File.Delete(_filePath); return; } if (latestTempIndex < latestOfficialIndex + WINNING_RUN_DISTANCE) { Console.WriteLine("[BLOCKS REFUSED] Not Winning dist!"); File.Delete(_filePath); return; } HardFork = true; } else { uint latestIndex = RequestLatestBlockIndex(false); if (firstTempIndex > latestIndex + 1) { Console.WriteLine("[BLOCKS REFUSED] Can't proccess blocks. "); File.Delete(_filePath); return; } // we check if we have a fork that contains specific index to mesure if (latestTempIndex < latestOfficialIndex + 1) { Console.WriteLine("[BLOCKS REFUSED] Can't proccess blocks. "); File.Delete(_filePath); return; } } //--------- get the shom data during validation process ... //----- we should load the shit . but like every 30 blocs or something (depending of distance in time between those blocks ) Block bfirst = GetBlockAtIndexInFile(firstTempIndex, _filePath); Block blast = GetBlockAtIndexInFile(latestTempIndex, _filePath); if (bfirst == null || blast == null) { Console.WriteLine("header incorrect!"); File.Delete(_filePath); return; } //----------- if (HardFork) { Print("hard forking"); Block currentBlockReading = GetBlockAtIndexInFile(firstTempIndex, _filePath); Block previousBlock = GetBlockAtIndex(firstTempIndex - 1); if (currentBlockReading == null || previousBlock == null) { Console.WriteLine("[BLOCKS REFUSED] block null "); File.Delete(_filePath); return; } List <uint> timestamps = new List <uint>(); uint TC = 0; for (uint i = firstTempIndex - 1; i >= 0; i--) { if (i == uint.MaxValue) { break; } Block b = GetBlockAtIndex(i); if (b == null) { Console.WriteLine("[BLOCKS REFUSED] block null "); File.Delete(_filePath); return; } timestamps.Add(b.TimeStamp); TC++; if (TC >= TIMESTAMP_TARGET) { break; } } uint MINTIMESTAMP = GetTimeStampRequirementB(timestamps); byte[] tempTarget = new byte[32]; if (isNewTargetRequired(firstTempIndex)) { // will just use gethashtarget with ComputeHashTargetB Block earlierBlock; if (previousBlock.Index + 1 <= TARGET_CLOCK) { earlierBlock = GetBlockAtIndex(0); // get genesis if (earlierBlock == null) { Console.WriteLine("[BLOCKS REFUSED] block null "); File.Delete(_filePath); return; } } else { earlierBlock = GetBlockAtIndex(previousBlock.Index + 1 - TARGET_CLOCK);// need also an update if (earlierBlock == null) { Console.WriteLine("[BLOCKS REFUSED] block null "); File.Delete(_filePath); return; } } tempTarget = ComputeHashTargetB(previousBlock, earlierBlock); } else { tempTarget = previousBlock.HashTarget; } List <UTXO> vUTXO = new List <UTXO>(); //< we will need temp file to avoid stackoverflow ( dont load this in RAM! ) while (true) { //---- byte[] reqtarget = ApplyTheSeaToTheCryptoPuzzle(tempTarget, Tidal.GetTidalAtSpecificTime(currentBlockReading.TimeStamp)); Tuple <bool, List <UTXO> > bV = IsBlockValid(currentBlockReading, previousBlock, MINTIMESTAMP, tempTarget, reqtarget, vUTXO); if (!bV.Item1) { File.Delete(_filePath); Console.WriteLine("[BLOCKS REFUSED] block not valid "); return; } vUTXO = bV.Item2; if (currentBlockReading.Index == latestTempIndex) { DownGradeUTXOSet(firstTempIndex - 1); DowngradeOfficialChain(firstTempIndex - 1); AddBlocksToOfficialChain(_filePath, needPropagate); return; } previousBlock = currentBlockReading; //* currentBlockReading = GetBlockAtIndexInFile(currentBlockReading.Index + 1, _filePath); //* if (currentBlockReading == null) { Console.WriteLine("[BLOCKS REFUSED] block not valid "); File.Delete(_filePath); return; } timestamps.RemoveAt(0); timestamps.Add(previousBlock.TimeStamp); MINTIMESTAMP = GetTimeStampRequirementB(timestamps); if (isNewTargetRequired(currentBlockReading.Index)) { Block earlierBlock; if (previousBlock.Index + 1 <= TARGET_CLOCK) { earlierBlock = GetBlockAtIndex(0); if (earlierBlock == null) { Console.WriteLine("[BLOCKS REFUSED] block not valid "); File.Delete(_filePath); return; } } else { if (previousBlock.Index + 1 - TARGET_CLOCK > latestOfficialIndex) { earlierBlock = GetBlockAtIndexInFile(previousBlock.Index + 1 - TARGET_CLOCK, _filePath); if (earlierBlock == null) { Console.WriteLine("[BLOCKS REFUSED] block not valid "); File.Delete(_filePath); return; } } else { earlierBlock = GetBlockAtIndex(previousBlock.Index + 1 - TARGET_CLOCK); if (earlierBlock == null) { Console.WriteLine("[BLOCKS REFUSED] block not valid "); File.Delete(_filePath); return; } } } tempTarget = ComputeHashTargetB(previousBlock, earlierBlock); } else { tempTarget = previousBlock.HashTarget; } } } else { // [1] we need to check if first temp index is lower than our highest forks index forks OR if first temp index is equal to latestOfficialIndex + 1 // [2] we need to find if Block currentBlockReading = GetBlockAtIndexInFile(firstTempIndex, _filePath); // we get like latesttempindex -> 2 if (currentBlockReading == null) { File.Delete(_filePath); Console.WriteLine("[BLOCKS REFUSED] block not valid "); return; } string[] forkfiles = Directory.GetFiles(_folderPath + "fork"); uint latestIndex = RequestLatestBlockIndex(false); // string _pathToGetPreviousBlock = ""; if (firstTempIndex != latestOfficialIndex + 1) // searching A fork : if firsttempindex(1) is not latestofficialindex (0) + 1 { Print("called"); latestIndex = RequestLatestBlockIndex(false); if (latestIndex > firstTempIndex - 1) { _pathToGetPreviousBlock = GetIndexBlockChainFilePath(firstTempIndex - 1); if (_pathToGetPreviousBlock == "") { File.Delete(_filePath); Console.WriteLine("[BLOCK REFUSED ]Can't find a fork to process those blocks. temp index : " + firstTempIndex); return; } } else { // check if we can find a fork with this specific block file ... goes here when lightfork ... string forkpath = FindMatchingFork(currentBlockReading); if (forkpath.Length == 0) { Console.WriteLine("[BLOCK REFUSED ]Can't find a fork to process those blocks. temp index : " + firstTempIndex); return; } else { _pathToGetPreviousBlock = forkpath; } Block bb = GetBlockAtIndexInFile(latestTempIndex, _filePath); if (bb == null) { Console.WriteLine("[BLOCKS REFUSED] block not valid "); File.Delete(_filePath); return; } if (isForkAlreadyExisting(bb)) { Console.WriteLine("[BLOCKS REFUSED] block already exist "); File.Delete(_filePath); return; } } } else { //_pathToGetPreviousBlock = GetLatestBlockChainFilePath(); // this is shit ... _pathToGetPreviousBlock = GetIndexBlockChainFilePath(firstTempIndex - 1); } Print(_pathToGetPreviousBlock); Block previousBlock = GetBlockAtIndexInFile(firstTempIndex - 1, _pathToGetPreviousBlock); if (previousBlock == null) { File.Delete(_filePath); Console.WriteLine("[BLOCKS REFUSED] block null "); return; } List <uint> timestamps = new List <uint>(); uint TC = 0; for (uint i = firstTempIndex - 1; i >= 0; i--) { if (i == uint.MaxValue) { break; } if (i > latestOfficialIndex) { Block b = GetBlockAtIndexInFile(i, _pathToGetPreviousBlock); if (b == null) { Console.WriteLine("[BLOCKS REFUSED] block null "); File.Delete(_filePath); return; } timestamps.Add(b.TimeStamp); } else { Block b = GetBlockAtIndex(i); if (b == null) { Console.WriteLine("[BLOCKS REFUSED] block null "); File.Delete(_filePath); return; } timestamps.Add(GetBlockAtIndex(i).TimeStamp); } TC++; if (TC >= TIMESTAMP_TARGET) { break; } } uint MINTIMESTAMP = GetTimeStampRequirementB(timestamps); Print(MINTIMESTAMP.ToString()); byte[] tempTarget = new byte[32]; if (isNewTargetRequired(firstTempIndex)) { // will just use gethashtarget with ComputeHashTargetB Block earlierBlock; if (latestOfficialIndex < previousBlock.Index + 1 - TARGET_CLOCK) { uint lastindexfile = RequestLatestBlockIndexInFile(_pathToGetPreviousBlock); if (lastindexfile < previousBlock.Index + 1 - TARGET_CLOCK) { earlierBlock = GetBlockAtIndexInFile(previousBlock.Index + 1 - TARGET_CLOCK, _filePath); if (earlierBlock == null) { Console.WriteLine("[BLOCKS REFUSED] block null "); File.Delete(_filePath); return; } } else { earlierBlock = GetBlockAtIndexInFile(previousBlock.Index + 1 - TARGET_CLOCK, _pathToGetPreviousBlock); // it means that we have an index shit... if (earlierBlock == null) { Console.WriteLine("[BLOCKS REFUSED] block null "); File.Delete(_filePath); return; } } } else { earlierBlock = GetBlockAtIndex(previousBlock.Index + 1 - TARGET_CLOCK); if (earlierBlock == null) { Console.WriteLine("[BLOCKS REFUSED] block null "); File.Delete(_filePath); return; } } tempTarget = ComputeHashTargetB(previousBlock, earlierBlock); Print((previousBlock.Index + 1).ToString()); } else { tempTarget = previousBlock.HashTarget; } List <UTXO> vUTXO = new List <UTXO>(); //< can go up to 1.2mb (including retrograde) in ram so it is ok... // we should update this vUTXO with every block of a fork if fork is needed... also if (_pathToGetPreviousBlock != GetLatestBlockChainFilePath()) // we absolutely not need to compute retrograde here we just update the fork { uint firstforkIndex = BitConverter.ToUInt32(GetBytesFromFile(4, 8, _pathToGetPreviousBlock), 0); for (uint i = firstforkIndex; i < previousBlock.Index + 1; i++) { Block b = GetBlockAtIndexInFile(i, _pathToGetPreviousBlock); if (b == null) { File.Delete(_filePath); return; } foreach (Tx TXS in b.Data) { bool _sFound = false; int sIndex = 0; bool _rFound = false; int rIndex = 0; UTXO rutxo = null; for (int a = 0; a < vUTXO.Count; a++) { if (vUTXO[a].HashKey.SequenceEqual(ComputeSHA256(TXS.sPKey))) { _sFound = true; sIndex = a; } if (vUTXO[a].HashKey.SequenceEqual(TXS.rHashKey)) { _rFound = true; rIndex = a; rutxo = vUTXO[a]; } } if (!_sFound) { vUTXO.Add(UpdateVirtualUTXOWithFullBlock(b, GetOfficialUTXOAtPointer(TXS.sUTXOP), false)); } else { vUTXO[sIndex] = UpdateVirtualUTXOWithFullBlock(b, vUTXO[sIndex], false); } if (!_rFound) { rutxo = GetOfficialUTXOAtPointer(TXS.rUTXOP); if (rutxo != null) { vUTXO.Add(UpdateVirtualUTXOWithFullBlock(b, GetOfficialUTXOAtPointer(TXS.rUTXOP), false)); } } else { vUTXO[rIndex] = UpdateVirtualUTXOWithFullBlock(b, rutxo, false); } } bool _mFound = false; int mIndex = 0; for (int a = 0; a < vUTXO.Count; a++) { if (b.minerToken.MinerPKEY.SequenceEqual(vUTXO[a].HashKey)) { _mFound = true; mIndex = a; } } if (!_mFound) { UTXO mutxo = GetOfficialUTXOAtPointer(b.minerToken.mUTXOP); if (mutxo != null) { vUTXO.Add(UpdateVirtualUTXOWithFullBlock(b, mutxo, false)); } } else { vUTXO[mIndex] = UpdateVirtualUTXOWithFullBlock(b, vUTXO[mIndex], false); } } } while (true) { byte[] reqtarget = ApplyTheSeaToTheCryptoPuzzle(tempTarget, Tidal.GetTidalAtSpecificTime(currentBlockReading.TimeStamp)); //---- Tuple <bool, List <UTXO> > bV = IsBlockValid(currentBlockReading, previousBlock, MINTIMESTAMP, tempTarget, reqtarget, vUTXO); if (!bV.Item1) { File.Delete(_filePath); return; } vUTXO = bV.Item2; // vutxo are update! if (currentBlockReading.Index == latestTempIndex) { if (_pathToGetPreviousBlock == GetLatestBlockChainFilePath()) { string newPath = GetNewForkFilePath(); File.Move(_filePath, newPath); Print("new fork added"); UpdatePendingTXFileB(newPath); VerifyRunState(needPropagate); // we should verify if newpath exist. if it is existing we broadcast it if (File.Exists(newPath) && needPropagate) { BroadcastQueue.Add(new BroadcastInfo(1, 1, newPath)); } return; } else { // we will need to concatenate those two forks... to write a new one ... string newForkPath = ConcatenateForks(_pathToGetPreviousBlock, _filePath, firstTempIndex); VerifyRunState(needPropagate); // we should verify if newpath exist. if it is existing we broadcast it if (File.Exists(newForkPath) && needPropagate) { BroadcastQueue.Add(new BroadcastInfo(1, 1, newForkPath)); } Print("fork has been append."); return; } } previousBlock = currentBlockReading; //* currentBlockReading = GetBlockAtIndexInFile(currentBlockReading.Index + 1, _filePath); //* if (currentBlockReading == null) { File.Delete(_filePath); Print("wrong index specified 3"); return; } timestamps.RemoveAt(0); timestamps.Add(previousBlock.TimeStamp); MINTIMESTAMP = GetTimeStampRequirementB(timestamps); if (isNewTargetRequired(currentBlockReading.Index)) { // will just use gethashtarget with ComputeHashTargetB Block earlierBlock; if (latestOfficialIndex < previousBlock.Index + 1 - TARGET_CLOCK) { uint lastindexfile = RequestLatestBlockIndexInFile(_pathToGetPreviousBlock); if (lastindexfile < previousBlock.Index + 1 - TARGET_CLOCK) { earlierBlock = GetBlockAtIndexInFile(previousBlock.Index + 1 - TARGET_CLOCK, _filePath); if (earlierBlock == null) { Print("[missing block]"); File.Delete(_filePath); return; } } else { earlierBlock = GetBlockAtIndexInFile(previousBlock.Index + 1 - TARGET_CLOCK, _pathToGetPreviousBlock); // it means that we have an index shit... if (earlierBlock == null) { Print("[missing block]"); File.Delete(_filePath); return; } } } else { earlierBlock = GetBlockAtIndex(previousBlock.Index + 1 - TARGET_CLOCK); if (earlierBlock == null) { Print("[missing block]"); File.Delete(_filePath); return; } } tempTarget = ComputeHashTargetB(previousBlock, earlierBlock); } else { tempTarget = previousBlock.HashTarget; } } } }
public TidalController() { Tidal = new Tidal(this); }
// Files Initialisation and Verification Methods public static void CheckFilesAtRoot() // check if file are in folder to process { _folderPath = AppDomain.CurrentDomain.BaseDirectory; Console.WriteLine(_folderPath); // set the stuff of tidal prediction if (!File.Exists(_folderPath + "tidaloracle")) { Console.WriteLine("will create tidaloracle file..."); if (!Tidal.GetTidalPrevision()) { Console.ReadKey(); Environment.Exit(0); return; } } else { Console.WriteLine("tidal file is here "); } if (!Tidal.SetLatestRequest()) { Console.ReadKey(); Environment.Exit(0); return; } ; Tidal.GetTidalAtSpecificTime((uint)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds); if (!File.Exists(_folderPath + "genesis")) { CreateGenesis(); } if (!Directory.Exists(_folderPath + "net")) { Directory.CreateDirectory(_folderPath + "net"); } else { Directory.Delete(_folderPath + "net", true); Directory.CreateDirectory(_folderPath + "net"); } if (!Directory.Exists(_folderPath + "blockchain")) { Directory.CreateDirectory(_folderPath + "blockchain"); File.WriteAllBytes(_folderPath + "blockchain/0", new byte[4]); AppendBytesToFile(_folderPath + "blockchain/0", File.ReadAllBytes(_folderPath + "genesis")); File.WriteAllBytes(_folderPath + "blockchain/1", new byte[4]); } if (!File.Exists(_folderPath + "utxos")) { File.WriteAllBytes(_folderPath + "utxos", new byte[4]); } if (!File.Exists(_folderPath + "ptx")) { File.Create(_folderPath + "ptx"); } if (!Directory.Exists(_folderPath + "fork")) { Directory.CreateDirectory(_folderPath + "fork"); } CURRENT_UTXO_SIZE = (uint)new FileInfo(_folderPath + "utxos").Length; UpdateHashTarget(); }
// Get Every Block mine since a tides and range times public static List <Tuple <float, Block> > GetBlocksMinedSinceNumberOfTides(uint _tidesNumber = 1, uint _startTime = 0, uint _secondOffset = 0) { List <Tuple <float, Block> > result = new List <Tuple <float, Block> >(); if (_startTime == 0) { _startTime = (uint)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; } if (_tidesNumber < 1) { _tidesNumber = 1; } uint unixTimestamp = _startTime + _secondOffset; uint startTimeStamp = unixTimestamp; uint endTimestamp = 0; uint tideCounter = 0; float lastwater_level = 0; int movement = 0; for (uint i = 0; i < 500; i++) // la ya 8 heure { float water_level = Tidal.GetTidalAtSpecificTime(unixTimestamp); if (lastwater_level < water_level) { if (movement == -1) // now sea level will start to increment { tideCounter++; } if (tideCounter == _tidesNumber) { endTimestamp = unixTimestamp; break; } movement = 1; } if (lastwater_level > water_level) { movement = -1; } lastwater_level = water_level; unixTimestamp -= 300; // get the water every five minutes } Block latestBlock = GetBlockAtIndex(RequestLatestBlockIndex(true)); if (latestBlock.TimeStamp < endTimestamp) { return(null); } result.Add(new Tuple <float, Block>(Tidal.GetTidalAtSpecificTime(latestBlock.TimeStamp), latestBlock)); for (uint i = latestBlock.Index; i >= 2; i--) { Block b = GetBlockAtIndex(i); if (b.TimeStamp < endTimestamp) { break; } else { result.Add(new Tuple <float, Block>(Tidal.GetTidalAtSpecificTime(b.TimeStamp), b)); } } return(result); }
// start time and range ? public static List <Tuple <float, uint> > GetTidalValuesInRangeOfTides(uint _tidesNumber = 1, uint _startTime = 0, uint _secondOffset = 0) { // the format is highest tidal timestamp -> lowest tidal timestamp ... -> repeat etc. if (_startTime == 0) { _startTime = (uint)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; } if (_tidesNumber < 1) { _tidesNumber = 1; } List <Tuple <float, uint> > result = new List <Tuple <float, uint> >(); uint unixTimestamp = _startTime + _secondOffset; uint startTimeStamp = unixTimestamp; uint tideCounter = 0; float lastwater_level = 0; int movement = 0; result.Add(new Tuple <float, uint>(Tidal.GetTidalAtSpecificTime(unixTimestamp), unixTimestamp)); for (uint i = 0; i < 500; i++) // la ya 8 heure { float water_level = Tidal.GetTidalAtSpecificTime(unixTimestamp); if (lastwater_level < water_level) { if (movement == -1) // now sea level will start to increment { tideCounter++; result.Add(new Tuple <float, uint>(Tidal.GetTidalAtSpecificTime(unixTimestamp + 300), unixTimestamp + 300)); } if (tideCounter == _tidesNumber) { break; } movement = 1; } if (lastwater_level > water_level) { if (movement == 1) { // now sea level will start to decrement // so this is a high peak result.Add(new Tuple <float, uint>(Tidal.GetTidalAtSpecificTime(unixTimestamp + 300), unixTimestamp + 300)); } movement = -1; } lastwater_level = water_level; unixTimestamp -= 300; // get the water every five minutes } Console.WriteLine(tideCounter); return(result); }
public static string MineBlock(List <Tx> TXS, Block prevBlock, byte[] pKey, uint mUTXOP, string WinBlockPath, uint clock_limit) { // Merkle root is build like this : index + ph + datasize + tx + timestamp + minertoken + hashtarget uint unixTimestamp = (uint)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; List <byte> dataBuilder = new List <byte>(); dataBuilder = AddBytesToList(dataBuilder, BitConverter.GetBytes(prevBlock.Index + 1)); dataBuilder = AddBytesToList(dataBuilder, prevBlock.Hash); dataBuilder = AddBytesToList(dataBuilder, BitConverter.GetBytes((uint)TXS.Count)); uint sum = 0; foreach (Tx TX in TXS) { dataBuilder = AddBytesToList(dataBuilder, TxToBytes(TX)); sum += TX.TxFee; } dataBuilder = AddBytesToList(dataBuilder, BitConverter.GetBytes(unixTimestamp)); uint currentMiningReward = GetMiningReward(prevBlock.Index + 1); uint MR = sum + currentMiningReward; MinerToken MT = new MinerToken(pKey, mUTXOP, MR); dataBuilder = AddBytesToList(dataBuilder, MinerTokenToBytes(MT)); byte[] HASH_TARGET; if (isNewTargetRequired(prevBlock.Index + 1)) //< will compute with the new hash target { Block earlier; if (RequestLatestBlockIndex(true) >= prevBlock.Index + 1 - TARGET_CLOCK) { earlier = GetBlockAtIndex(prevBlock.Index + 1 - TARGET_CLOCK); if (earlier == null) { Console.WriteLine("previous block was null during mining proccess."); return(""); } } else { earlier = GetBlockAtIndexInFile(prevBlock.Index + 1 - TARGET_CLOCK, WinBlockPath); if (earlier == null) { Console.WriteLine("previous block was null during mining proccess."); return(""); } } HASH_TARGET = ComputeHashTargetB(prevBlock, earlier); } else { HASH_TARGET = prevBlock.HashTarget; } dataBuilder = AddBytesToList(dataBuilder, HASH_TARGET); byte[] CLEAN_HASH_TARGET = HASH_TARGET; float water_level = Tidal.GetTidalAtSpecificTime(unixTimestamp); HASH_TARGET = ApplyTheSeaToTheCryptoPuzzle(HASH_TARGET, water_level); byte[] sha = ComputeSHA256(ListToByteArray(dataBuilder)); sha = ComputeSHA256(sha); //< double hash function to avoid collision or anniversary attack byte[] nonceByte = new byte[4]; Random rd = new Random(); rd.NextBytes(nonceByte); uint nonce = BitConverter.ToUInt32(nonceByte, 0); //uint nonce = 0; // on va dire que c'est un random uint entre 0 et uint.maxvalue Stopwatch sw = new Stopwatch(); sw.Start(); Stopwatch sw2 = new Stopwatch(); sw2.Start(); uint trycounter = 0; while (true) { List <byte> Databuilder = new List <byte>(); Databuilder = AddBytesToList(Databuilder, BitConverter.GetBytes(nonce)); Databuilder = AddBytesToList(Databuilder, sha); byte[] hash = ListToByteArray(Databuilder); hash = ComputeSHA256(hash); if (isNonceGolden(hash, HASH_TARGET)) { Print("[CONGRATS] YOU MINED A BLOCK!!"); Block WinnerBlock = new Block(prevBlock.Index + 1, sha, prevBlock.Hash, TXS, unixTimestamp, MT, CLEAN_HASH_TARGET, nonce); // reapply hash to the stuff PrintBlockData(WinnerBlock); Console.WriteLine("will write at " + WinBlockPath); arduino.SendTick("5"); // go sing the coucou arduino.HashToClock(hash); if (File.Exists(WinBlockPath)) { Console.WriteLine("will write a new fi le at " + WinBlockPath); OverWriteBytesInFile(0, WinBlockPath, BitConverter.GetBytes(WinnerBlock.Index)); AppendBytesToFile(WinBlockPath, BlockToBytes(WinnerBlock)); } else { Console.WriteLine("append bytes at " + WinBlockPath); File.WriteAllBytes(WinBlockPath, BitConverter.GetBytes(WinnerBlock.Index)); AppendBytesToFile(WinBlockPath, BlockToBytes(WinnerBlock)); } Console.WriteLine("shoud have write at " + WinBlockPath); UpdatePendingTXFile(WinnerBlock); return(WinBlockPath); } else { if (sw.Elapsed.Seconds > 5) { Console.WriteLine("______________________________________"); Console.WriteLine(" [Mining report] "); Console.WriteLine("total attempts : " + trycounter); Console.WriteLine("last hash produced :" + SHAToHex(hash, false)); Console.WriteLine("index : " + (prevBlock.Index + 1).ToString()); Console.WriteLine("previous hash : " + SHAToHex(prevBlock.Hash, false)); Console.WriteLine("hash target : " + SHAToHex(HASH_TARGET, false)); Console.WriteLine("water level : " + water_level); Console.WriteLine("______________________________________"); sw.Restart(); } if (sw2.Elapsed.Seconds > clock_limit) { Console.WriteLine("Mining time limit reached. Mining aborted for this specific new block. "); return(""); } if (nonce == uint.MaxValue) { rd.NextBytes(nonceByte); nonce = BitConverter.ToUInt32(nonceByte, 0); } trycounter++; nonce++; } } }