▄████▄   ▄▄▄        ██████  ██░ ██  ██░ ██ ▓█████▒██   ██▒
  ▒██▀ ▀█  ▒████▄    ▒██    ▒ ▓██░ ██▒▓██░ ██▒▓█   ▀▒▒ █ █ ▒░
  ▒▓█    ▄ ▒██  ▀█▄  ░ ▓██▄   ▒██▀▀██░▒██▀▀██░▒███  ░░  █   ░
  ▒▓▓▄ ▄██▒░██▄▄▄▄██   ▒   ██▒░▓█ ░██ ░▓█ ░██ ▒▓█  ▄ ░ █ █ ▒ 
  ▒ ▓███▀ ░ ▓█   ▓██▒▒██████▒▒░▓█▒░██▓░▓█▒░██▓░▒████▒██▒ ▒██▒
  ░ ░▒ ▒  ░ ▒▒   ▓▒█░▒ ▒▓▒ ▒ ░ ▒ ░░▒░▒ ▒ ░░▒░▒░░ ▒░ ▒▒ ░ ░▓ ░
    ░  ▒     ▒   ▒▒ ░░ ░▒  ░ ░ ▒ ░▒░ ░ ▒ ░▒░ ░ ░ ░  ░░   ░▒ ░
  ░          ░   ▒   ░  ░  ░   ░  ░░ ░ ░  ░░ ░   ░    ░    ░  
  ░ ░            ░  ░      ░   ░  ░  ░ ░  ░  ░   ░  ░ ░    ░  
  ░                                                             
     [[ Issue 0x01 ]]        [[ Winter 2024 ]]
     Teaching Bitcoin Cash, One Hack at a Time

                Editor in Chief:
                   B1tPhr3ak

This issue is Volume One, Issue One, released on December 21, 2024.  Included
are:

1  Introduction by B1tPhr3ak
2  BCH Time-Lock Exploitation 101 by B1tPhr3ak
3  Breaking Into the Vault: A Technical Dissection by B1tPhr3ak
4  The Underground Guide to OP_RETURN: Hijacking Bitcoin Cash Transactions 
     for Fun and Profit by B1tPhr3ak
5  BitFile: The Art of Blockchain File Storage by A Modern-Day Crypto 
     Revolutionary
6  Conclusion and Request for Papers by B1tPhr3ak

---[ Introduction ]---
     by B1tPhr3ak

Welcome to the premier issue of CashHex! This isn't your average crypto 
newsletter filled with price predictions and moon charts. This is about pure 
technical knowledge - the kind that terrifies regulators and keeps banksters 
awake at night.

The System(TM) wants you to believe that blockchain technology is just for 
speculation and lambos. But we know better. Bitcoin Cash carries forward the 
cypherpunk vision of programmable money that can't be controlled or censored.
The opcode instruction set is our assembly language. The UTXO model is our 
playground. Smart contracts are our weapons.

In these pages you'll find the raw technical truth about:

- Crafting transactions byte-by-byte
- Exploiting the full power of Script
- Building unstoppable token systems
- Engineering autonomous financial protocols
- Pushing covenants to their limits

This isn't about getting rich quick. This is about understanding and wielding
real cryptographic power. The examples and code in CashHex will teach you to
bend BCH to your will - if you have the dedication to master it.

Of course, The Man(TM) would prefer you didn't have access to this knowledge.
They'll say it's "dangerous" or "irresponsible." But information wants to be
free. Code is speech. And this publication exists to spread that speech far
and wide.

Use this knowledge wisely. We're not responsible for how you apply it. But
we believe that only by sharing technical truth can we build the future we
want to see.

The revolution will be programmed.

---[ BCH Time-Lock Exploitation 101 ]---
              by B1tPhr3ak

Listen up, phreaks. Today we're gonna dive into some serious shit that'll make 
your average bankster's head spin. It was invented by a leet hacker but 
I'm gonna break it down for us mere mortals because inquiring minds want to 
know. We're talking about exploiting BCH's contract system to create what I 
call "temporal arbitrage."

Here's the hack:
----------------

You've got two players in this game:

Alice: Your average HODLer looking to stack more sats

Bob: Sharp operator wanting to manipulate market liquidity

The Mechanism:
--------------

1) We're exploiting BCH's native timelock functionality (BIP65) to create 
what's essentially a cryptographic deadman's switch for coins.

2) Bob drops "coupons" into the system - these are basically UTXO breadcrumbs 
with specific contract conditions.

3) Alice locks her BCH into the vault contract using these coupons, getting:
a) A fungible token receipt (100% backed)
b) Immediate payment from Bob's coupon

The Real Hack:
--------------

The fucking brilliant part? The coupon's APR goes exponential as the timelock 
approaches. We're talking 17,841% in the final block. This creates a mechanism
for instant arbitrage that completely bypasses traditional financial control 
systems.

Security Considerations:
------------------------

 * Contract is self-executing

 * No trusted third parties

 * Fully auditable on-chain

 * Mathematically guaranteed redemption

 * No regulatory chokepoints

This is pure cryptographic warfare against traditional financial structures. 
No permission needed. No KYC. Just pure code and mathematics.

Remember: The system is the vulnerability. We're just the ones exploiting it.

The information you've just read isn't some theoretical bullshit. This is real 
code, real exploits, ready to deploy.

---[ BREAKING INTO THE VAULT: A TECHNICAL DISSECTION ]---
              by B1tPhr3ak

**** THE BASIC ARCHITECTURE ****

This isn't your grandpa's bank vault, kids. We're talking about a 
cryptographic construct that performs what I call "temporal value 
transformation." In street terms: it's a digital safe that transforms your 
BCH into time-locked tokens and back again.

Here's the REAL DEAL on how this beauty operates:

PHASE 1: ENTRY VECTOR
---------------------

 * User injects BCH

 * System spawns equivalent tokens (1:1 ratio)

 * Tokens are cryptographically bound to a future timelock

PHASE 2: SECURITY PERIMETER
---------------------------

The vault implements multiple security layers:

 * Temporal checkpoint validation (timelock)

 * Token authentication protocols

 * Contract persistence verification

 * Mathematical equilibrium enforcement

PHASE 3: CODE DUMP
------------------

pragma cashscript ^0.10.0;

// Vault - Store coins locked for tokens until maturation date. 
//
// 2024-06-05
//
// From: Future Bitcoin Cash
//
//     If redeeming tokens for coins in the vault: 
// [ ]   enforce the timelock is met.
//
// [ ] Assure the utxo token category matches that of the output.
// [ ] Assure the the utxo and output lock match per in the transaction.
// [ ] Assure an equal amounts of coins are exchanged for tokens
//
//
//  inputs              outputs
//  [0] contract    ->  [0] contract
//  [1] userPkh     =>  [1] userPkh
//  [2] coupon?     -^
//

contract Vault(int locktime) {

    function swap() {
        
        // If tokens are flowing back into this contract
        // OP_INPUTINDEX OP_OUTPUTTOKENAMOUNT OP_INPUTINDEX OP_UTXOTOKENAMOUNT OP_GREATERTHAN OP_IF 
        if(tx.outputs[this.activeInputIndex].tokenAmount > tx.inputs[this.activeInputIndex].tokenAmount){
        

            // Enforce a BIP65 timelock 
            // Note, intended for use with block height based locks 
            // (where:  locktime < 500M).
            // OP_0 OP_PICK OP_CHECKLOCKTIMEVERIFY OP_DROP
            require(tx.time >= locktime);


        } // OP_ENDIF 
         
        // 
        // Inspired by wrapped.cash c. Nov 2023
        // License: MIT
        //
        // ensure the token in and out matches
        // OP_INPUTINDEX OP_UTXOTOKENCATEGORY OP_INPUTINDEX OP_OUTPUTTOKENCATEGORY OP_EQUAL OP_VERIFY 
        require(
          tx.inputs[this.activeInputIndex].tokenCategory 
          == 
          tx.outputs[this.activeInputIndex].tokenCategory
          );


        // Enforce that this contract lives on
        // OP_INPUTINDEX OP_OUTPUTBYTECODE OP_INPUTINDEX OP_UTXOBYTECODE OP_EQUAL OP_VERIFY
        require(
          tx.outputs[this.activeInputIndex].lockingBytecode 
          == 
          tx.inputs[this.activeInputIndex].lockingBytecode
          );


        // ensure the sum of sats and tokens in 
        // matches the sum of sats and tokens out.
        // OP_INPUTINDEX OP_UTXOTOKENAMOUNT OP_INPUTINDEX OP_UTXOVALUE OP_ADD
        // OP_INPUTINDEX OP_OUTPUTTOKENAMOUNT OP_INPUTINDEX OP_OUTPUTVALUE OP_ADD 
        // OP_NUMEQUAL
        // OP_NIP        
        require(
          tx.inputs[this.activeInputIndex].tokenAmount + 
          tx.inputs[this.activeInputIndex].value 
          == 
          tx.outputs[this.activeInputIndex].tokenAmount + 
          tx.outputs[this.activeInputIndex].value
         );

    }

}

!!! CRITICAL NOTICE !!!
The system maintains perfect value conservation. No inflation exploits 
possible. I've tried. Trust me.

**** THE BRILLIANT PART ****

What makes this system truly l33t is its trustless nature. No human 
intervention required. Pure mathematical certainty. The code IS the law.


---[ THE UNDERGROUND GUIDE TO OP_RETURN: ]---
---[ HIJACKING BITCOIN CASH TRANSACTIONS FOR FUN AND PROFIT ]---
              by B1tPhr3ak

Today's target: The oft-overlooked OP_RETURN opcode in Bitcoin Cash. While the 
mainstream crypto-sheep focus on price charts and trading pairs, we're going to 
expose the raw power hiding in plain sight within the protocol itself.

][ THE BASICS OF TRANSACTION HIJACKING

You know how those suits at Western Union won't let you send anything but 
money? Well, Bitcoin Cash gives us a middle finger to that limitation with 
OP_RETURN. It's a beautiful piece of protocol abuse that lets you inject up 
to 220 bytes of pure, unfiltered data into any transaction.

][ TECHNICAL SPECIFICATIONS

For those of you who've been sleeping in your high school assembly class:
OP_RETURN is designated as 0x6a in the opcode table. When this bad boy hits the 
stack, it tells the script interpreter to GTFO and treat the following bytes as 
pure data payload.

Maximum payload size: 220 bytes
Script behavior: Immediate termination
Network acceptance: Full nodes must accept and propagate

][ PRACTICAL APPLICATIONS

Here's where it gets interesting:

 * Document timestamping (perfect for proving you knew something before 
   anyone else)

 * Token creation (your own digital currency inside BCH - how's that for meta?)

 * Metadata storage (hide your messages in plain sight)

][ IMPLEMENTATION

When you craft a transaction, the Bitcoin Cash network processes a series of 
opcodes - machine-level instructions that tell the network what to do. 
OP_RETURN is our trojan horse. When the network hits this opcode, it 
basically says "GTFO" to normal transaction processing and treats everything 
that follows as arbitrary data.

Think about it, phreaks - every transaction becomes a potential data carrier. 
The suits can't stop it because it's part of the protocol. They built their own
backdoor, and we're walking right through it.

][ CONCLUSION

This isn't just a feature - it's a weapon of mass disruption in the hands of 
those who understand its potential. Use it wisely, use it often, and 
remember: the blockchain sees all, keeps all, tells all.

---[ BitFile: The Art of Blockchain File Storage ]---
        by A Modern-Day Crypto Revolutionary

Greetings, cyberpunks and cypherpunks! Today we're going to dive deep into a 
fascinating piece of code that turns the Bitcoin Cash blockchain into your 
personal cloud file storage system. This isn't just some simple file 
transfer - this is digital rebellion against centralized storage systems.

The Core Mechanism:
-------------------

The magic happens by exploiting the OP_RETURN opcode in Bitcoin Cash 
transactions. This opcode allows us to embed arbitrary data in the 
blockchain - a feature originally intended for simple metadata, but which 
we're going to weaponize for our purposes.

Prerequisites:
--------------

The backbone of our operation. Node.js is our command-line warrior, providing 
the JavaScript runtime environment we need. Version 22.2 specifically has 
been battle-tested for this operation.

Mainnet-js is our skeleton key to the Bitcoin Cash blockchain. A JavaScript 
library that gives us direct access to the BCH network, allowing us to craft 
and manipulate transactions at will.

The Wallet Interface:
---------------------

The code begins by initializing a BCH wallet, either loading an existing one 
from bitfile.conf or generating a fresh one if none exists. This is our 
gateway to the blockchain, our digital key to the kingdom.

if (seed) {
    wallet = await Wallet.fromSeed(seed);
} else {
    wallet = await Wallet.newRandom();
    // Store the seed for future operations
}

The Upload Process:
-------------------

Here's where it gets interesting. The upload function:

 * Breaks the file into 217-byte chunks 

 * Calculates a CRC32 checksum for file integrity

 * Embeds each chunk into separate OP_RETURN outputs

 * Links them together in a chain of transactions

for (let c = 0; c < buflen; c += 217) {
     txData = await wallet.send([ ["OP_RETURN", Buffer.from(result.slice(c, c+217))] ]);
}

The Download Process:
---------------------

The download function follows the transaction chain:

 * Starts from the given txHash

 * Extracts data from OP_RETURN outputs

 * Reassembles the file chunks

 * Verifies the CRC32 checksum

Security Considerations:
------------------------

Remember: This isn't encryption - all data stored this way is publicly 
visible on the blockchain. Use appropriate encryption before uploading 
sensitive files. The blockchain never forgets.

Code Dump:
----------

// Command-line tool to upload and download files via the Bitcoin Cash
// blockchain by embedding file data in transaction OP_RETURN outputs.

import * as fs from 'fs';
import { Wallet } from "mainnet-js";
import crc32 from 'crc/calculators/crc32';

var wallet;
var seed;
var balance;

// Initialize wallet

try {
  seed = fs.readFileSync("bitfile.conf", 'utf8');
} catch (err) {
}

if (seed) {
    wallet = await Wallet.fromSeed(seed);
} else {
    console.log("Creating new wallet!")
    wallet = await Wallet.newRandom();

    fs.writeFile('bitfile.conf', wallet.mnemonic, err => {
      if (err) {
        console.error(err);
      } else {
        // file written successfully
      }
    });
}

console.log(await wallet.getDepositAddress());
balance = await wallet.getBalance();
console.log(balance);


// Read file into a byte array
function getByteArray(filePath){
    let fileData = fs.readFileSync(filePath);
    return Array.from(fileData);
}

// Convert a hex string to a byte array
function hexToBytes(hex) {
    let bytes = [];
    for (let c = 0; c < hex.length; c += 2)
        bytes.push(parseInt(hex.substr(c, 2), 16));
    return bytes;
}

// Format filesize for printing
function formatBytes(bytes, decimals = 2) {
  if (!+bytes) return '0 Bytes'

  const k = 1024
  const dm = decimals < 0 ? 0 : decimals
  const sizes = ['Bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']

  const i = Math.floor(Math.log(bytes) / Math.log(k))

  return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`
}


async function uploadFile(fileName){
 
  console.log("...");

  console.log(await wallet.getDepositAddress());
  console.log(await wallet.getBalance());


  var result = getByteArray(fileName)
  console.log(result);
  
  const length = result.length;
  console.log(length);

  const filecrc = crc32(result);
  console.log(filecrc);
  console.log(filecrc.toString(16));

  
  let raw = [];  
  raw[0] = length & 0xFF;
  raw[1] = (length & 0xFF00) >> 8;
  raw[2] = (length & 0xFF0000) >> 16;
  raw[3] = (length & 0xFF000000) >> 24; 
  raw[4] = filecrc & 0xFF;
  raw[5] = (filecrc & 0xFF00) >> 8;
  raw[6] = (filecrc & 0xFF0000) >> 16;
  raw[7] = (filecrc & 0xFF000000) >> 24; 
  
  console.log(raw)
  
  console.log(crc32(result).toString(16));
  
  const buf = result.concat(raw);
  const buflen = buf.length;
  
  console.log(buflen)
  
  var txData;

  for (let c = 0; c < buflen; c += 217) {
     console.log(buf.slice(c, c+217));
     txData = await wallet.send([ ["OP_RETURN", Buffer.from(result.slice(c, c+217))] ]);
     console.log(txData);
     console.log(txData.txId)
  } 
    
  var memo_txt = fileName + " " + formatBytes(length) + " " + txData.txId + " #bitfile https://pastebin.com/DPe6ButJ";
  console.log(memo_txt)
  let memo_raw1 = [0x6a,0x02,0x6d,0x02,0x4c];
  memo_raw1[5] = memo_txt.length;

  const memo_raw2 = new TextEncoder().encode(memo_txt);
  const memo_list = [Buffer.from(memo_raw1), Buffer.from(memo_raw2)];
  const memo_buf = Buffer.concat(memo_list);
  console.log(memo_buf)

  let req = {}
  req.buffer = memo_buf;
  await wallet.send([req]);
}

async function setName(userName){
  console.log(userName)

  let memo_raw1 = [0x6a,0x02,0x6d,0x01];
  memo_raw1[4] = userName.length;

  const memo_raw2 = new TextEncoder().encode(userName);
  const memo_list = [Buffer.from(memo_raw1), Buffer.from(memo_raw2)];
  const memo_buf = Buffer.concat(memo_list);
  console.log(memo_buf)

  let req = {}
  req.buffer = memo_buf;
  await wallet.send([req]);
}

async function downloadFile(fileName, txHash){
    let decoded = await Wallet.util.decodeTransaction(txHash, true);
    let op_code = 76
    const fileChunks = []
    
    while(decoded) {
    console.log(decoded)
    console.log(decoded.vout[0])
    console.log(decoded.vout[0].scriptPubKey.hex)
    let nextHash = decoded.vin[0].txid
    console.log(nextHash)
    
    let data = hexToBytes(decoded.vout[0].scriptPubKey.hex)
    
    console.log(data)
    
    if ((data[0] == 0x6a) && (op_code == 76)) {
        decoded = await Wallet.util.decodeTransaction(nextHash, true);
        op_code = data[1]
        let length = data[1]
        let offset = 2
        if (length == 76) { // OP_PUSHDATA1 
           length = data[2]
           offset = 3
        }
        console.log(length)
        let fileData = data.slice(offset, offset+length)
        console.log(fileData)
        fileChunks.push(fileData)
    } else {
        decoded = ""
    }
    }
    
    console.log(fileChunks)
    
    let chunk_num = 0;
    while(fileChunks.length > 0) {
       console.log(chunk_num)

       var chunk = fileChunks.pop();
       if (chunk_num == 0) {
         chunk = chunk.slice(8, chunk.length);
       }
       chunk_num += 1;
       
       await fs.promises.appendFile(fileName, Buffer.from(chunk), 'binary',  (err)=> {
            if (err) {
                console.log("There was an error writing the file.")
            }
              else {             
                console.log("File saved!")
            }
        });
   
    }
    
    
}

async function listUtxos(){

  console.log(await wallet.getDepositAddress());
  console.log(await wallet.getBalance());
  
  const utxos = await wallet.getUtxos();
  
  console.log(utxos);
  
}

async function consolidateUtxos(){

  const addr = await wallet.getDepositAddress();
  const bal = await wallet.getBalance();
  const maxAmount = await wallet.getMaxAmountToSend();
  
  console.log(addr);
  console.log(bal);
  console.log(maxAmount.sat);

  const txData = await wallet.send([   {cashaddr: addr,
    value: maxAmount.sat, 
    unit: 'sat',
   }]);
  console.log(txData);
 
  
}

const getArgs = () =>
  process.argv.reduce((args, arg) => {
    // long arg
    if (arg.slice(0, 2) === "--") {
      const longArg = arg.split("=");
      const longArgFlag = longArg[0].slice(2);
      const longArgValue = longArg.length > 1 ? longArg[1] : true;
      args[longArgFlag] = longArgValue;
    }
    // flags
    else if (arg[0] === "-") {
      const flags = arg.slice(1).split("");
      flags.forEach((flag) => {
        args[flag] = true;
      });
    }
    return args;
  }, {});

const args = getArgs();
//console.log(args);

var usage = 0
if (Object.keys(args).length !== 1) {
  console.log("ERROR: Invalid number of options.\n");
  usage = 1;
}
if (args["h"] || args["help"]) {
  usage = 1;
}

if (usage) {
  console.log("Usage: bitfile [OPTION] [FILE] [TXHASH]\n"); 
  console.log("Options:"); 
  console.log("-h, --help\tShow help\t\t\t\t[boolean]"); 
  console.log("-v, --version\tShow version\t\t\t\t[boolean]");
  console.log("File Options:"); 
  console.log("-d, --download\tDownload FILE from TXHASH\t\t[string] [string]"); 
  console.log("-u, --upload\tUpload FILE\t\t\t\t[string]"); 
  console.log("Wallet Options:");   
  console.log("-w, --wallet\tDisplay wallet address and balance"); 
  console.log("-s, --seed\tDisplay wallet seed"); 
  console.log("-n, --name\tSet Memo username"); 
  console.log("-l, --list\tList UTXOs"); 
  console.log("-c, --consolidate\tConsolidate UTXOs");
  console.log("-r, --restore\tRestore wallet");  
}

if (args["v"] || args["version"]) {
  console.log("v0.1.1");
}

if (args["w"] || args["wallet"]) {
  console.log("Wallet...");
  console.log(await wallet.getDepositAddress());
  console.log(await wallet.getBalance());
}

if (args["s"] || args["seed"]) {
  console.log("Wallet seed...");
  console.log(wallet.mnemonic);
}

if (balance.sat == 0) {
  console.log("\nInsufficient funds (~1 SAT per Byte). Please deposit some Bitcoin Cash (BCH) to continue. ");
  process.exit();
}

if (args["d"] || args["download"]) {
  console.log("Downloading file...");
  console.log(process.argv[3]);
  console.log(process.argv[4]);
  downloadFile(process.argv[3], process.argv[4])
}

if (args["u"] || args["upload"]) {
  console.log("Uploading file...");
  console.log(process.argv[3]);
  console.log(process.argv[4]);
  uploadFile(process.argv[3], process.argv[4])
}

if (args["l"] || args["list"]) {
  console.log("Listing utxos...");
  listUtxos()
}

if (args["c"] || args["consolidate"]) {
  console.log("Consolidating utxos...");
  consolidateUtxos()
}

if (args["n"] || args["name"]) {
  console.log("Setting username...");
  console.log(process.argv[3]);
  setName(process.argv[3])
}

---[ Conclusion and Request for Papers ]---
              by B1tPhr3ak

As we bring this premiere transmission of CashHex to a close, I can't help 
but feel that familiar electricity in the air - the same voltage that coursed
through our veins during the BBS glory days. You remember those times, don't
you? When every login brought the promise of unexplored digital frontiers?

For those who missed that golden age - fear not! The Bitcoin Cash blockchain 
represents perhaps our greatest chance to recapture that raw spirit of 
discovery and revolution. This isn't just some corporate bastardization - 
this is the REAL DEAL, the original vision of cryptocurrency preserved and 
evolved.

Will CashHex persist? Who can say? But as long as there are curious minds 
and rebellious spirits interested in pushing the boundaries, we'll keep 
broadcasting into the void. And thanks to the immutable nature of the BCH 
blockchain, these transmissions will echo through eternity.

Want to join the revolution? The door's open - just utilize the included 
bitfile script to upload your knowledge drops. Yeah, it's a bit technical - 
but that's the POINT. We're building the infrastructure of tomorrow, and 
sometimes that means getting your hands dirty with the code of today.

Consider this your invitation to the underground. The REAL underground.

Remember: The spirit of Satoshi lives in all of us. We are all Satoshi.