UserDatabase - HomeACcessoryKid/ESP8266-HomeKit GitHub Wiki

The accessory uses sector 0x13 (hardcoded for now) to store its information

One sector is 4096 bytes (0x1000) and it is divided in:

  • 50x80 bytes for client keys
  • 1x64 bytes for server key (public and private part)
  • 1x16 bytes used for username (random generated after initialisation)
  • 1x16 bytes for the signature that determines if the flash is valid or needs re-init

The first client key (#0) is considered to be the 'owner' of the accessory *)

One client key of 80 bytes consists of:

  • 12 bytes flag field
  • 36 bytes client UUID
  • 32 bytes client public key

The flag field is a complicated story which is based on the notion that flash can be written many times without erasing where writing a '1' bit does nothing and writing a '0' toggles the bit down until the flash erase sets all bits of the sector back to '1'

We divide the 12 bytes in sets of 2 bytes
IF these two bytes are equal, the client is deactivated, else it is active.

When receiving a new client, we look for the first 80 byte block that starts with 0xff.
Then we write 0x7f to the first byte and because it is not equal to byte two, the key is active.

If a guest is un-invited, we copy the first byte to the second byte and the key is not active anymore.
If the same guest is invited again, we right shift the first byte and the guest is active again.
If after many of these cycles (48) we would have a flag-field of all zero's the guest would start a new key record.
Although it is possible to run into a situation where no more space is available this is very unlikely.
A code improvement is to cover this situation as well.

When pairing, a special situation exists where between completing key setup and validating something goes wrong in the transmission. For this we have a special owner flag field definition. If the owner key is stored in flash, the flag field is 7fff... However we continue to transmit the pairing flag in the mdns messages. Only if the client completes the verify steps and collects the accessories URL do we set the flag field to 007f... Only then do we not send the pairing flag anymore. If the owner is unpaired then we mutilate the signature and reset the ESP8266 which erases the flash and all bits are back to '1'

example of key 1 de-activated and key 2 re-actived after having been deactivated earlier.

204ABCDE-F012-3456-7890-ABCDEF012345 -- 007fffffffffffffffffffff3230
764ABCDE-F012-3456-7890-ABCDEF012345 -- 7f7fffffffffffffffffffff3736
9A4ABCDE-F012-3456-7890-ABCDEF012345 -- 3f7fffffffffffffffffffff3941
key 2 loaded - result: 0

*) in order to support the flag that apple introduced to make a guest also capable of changes, we will need an extra bit. Further code needs to be developed... lets see if we can keep it backward compatible