1

https://github.com/solana-labs/break/blob/master/program/src/lib.rs

use solana_program::{
    account_info::AccountInfo, entrypoint, entrypoint::ProgramResult, pubkey::Pubkey,
};

entrypoint!(process_instruction);
fn process_instruction<'a>(
    _program_id: &Pubkey,
    accounts: &'a [AccountInfo<'a>],
    instruction_data: &[u8],
) -> ProgramResult {
    // Assume a writable account is at index 0
    let mut account_data = accounts[0].try_borrow_mut_data()?;

    // xor with the account data using byte and bit from ix data
    let index = u16::from_be_bytes([instruction_data[0], instruction_data[1]]);
    let byte = index >> 3;
    let bit = (index & 0x7) as u8;
    account_data[byte as usize] ^= 1 << (7 - bit);

    Ok(())
}

This is from one of their example applications, really not sure what to make of this, or where one might even begin to look in to understanding what the intent is here and how it functions..

Thanks in advance.


EDIT: Is this done to create a program-derived address? I found this on their API, and the above seems to make sense as an implementation of this I would imagine.

Charles
  • 405
  • 4
  • 13
  • 1
    As documented in the [README](https://github.com/solana-labs/break/blob/master/README.md): "*Each transaction will set a bit in the state within a Break program account, so each transaction can be uniquely identified by the bit it sets.*" The XOR operation is flipping the relevant bit. – eggyal May 19 '21 at 12:00

1 Answers1

2

1 << n sets nth bit of what's called a mask, such as 1 << 1 = 0010.

XOR is an useful operation that allows comparing bits, and in this case, it makes use of that property. If current bit is 0, it will be set to 1, and if it is 1, it will be set to 0.

Using the mask from above, we can select one single specific bit to compare, or in this case, switch based on what value it currently is.

1111 ^ 0010 = 1101, the result is a difference, with the bit that matched being set to 0.

1101 ^ 0010 = 1111, every single bit here is different, and so the bit that didn't match is also set to 1.


In short, it toggles a bit, it is a common idiom in bit manipulation code.

bits ^= 1 << n

Related: https://stackoverflow.com/a/47990/15971564

Kaihaku
  • 129
  • 6