@startuml
!include common.puml
$title(Chit Chain Consensus Protocol)
actor "Stock Holder" as vendor
database "Stock DB" as stock
database "Foil DB" as foil
actor "Foil Holder" as client

alt Stock originates/validates chit
  vendor	->>	stock:		Apply validating signature to chit
  stock		->>	foil:		Transmit new valid Chit\nwith validating signature\nProposed endHash: propHash
  foil		->>	foil:		Add/link new valid chit

  alt Foil agrees with stock's proposed endhash
    foil		->>	foil:		Ratchet forward\nackHash = propHash
    foil		->>	stock:		Acknowledge propHash
    stock		->>	stock:		Ratchet forward\nackHash = propHash
    note over stock: DONE
  end

else Foil originates/validates chit
  client	->>	foil:		Apply validating signature to chit
  foil		->>	stock:		Transmit new valid Chit\nwith validating signature\nAnd new endHash

  alt Stock agrees with new endHash
    stock		->>	stock:		Ratchet forward\nackHash = endHash
    note over stock: DONE
  end
  
  stock		->>	foil:		Compare my list of unlinked chits
end

foil		->>	stock:		Send chits since last ackHash\nand new endHash
    
alt All newly received chits are valid
  stock		->>	stock:		Apply chits\nRatchet forward\nackHash = endHash
else Can't reconcile/accept received chits
  stock		->>	vendor:		Report error to user
  stock		->>	foil:		Report error
  foil		->>	client:		Report error to user
end

alt Does stock still have any valid, unlinked chits
  stock		->>	foil:		Requeue/retry regular\nchit transmission to foil\n(return to top of diagram)
end

@enduml
